<?php

namespace app\supplier\controller;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use app\api\model\Postdatadb;
use app\erp\model\BrandApidb;
use app\erp\model\Branddb;
use app\erp\model\Buildtpldb;
use app\erp\model\Cartdb;
use app\erp\model\ComBranddb;
use app\erp\model\ComOrderdb;
use app\erp\model\Expressdb;
use app\erp\model\Goodsdb;
use app\erp\model\GoodsPriceLogdb;
use app\erp\model\Invoicedb;
use app\erp\model\Jddb;
use app\erp\model\Jdpricedb;
use app\erp\model\JunApiResultdb;
use app\erp\model\JunResultdb;
use app\erp\model\Kdresultdb;
use app\erp\model\Memberdb;
use app\erp\model\MonthContractdb;
use app\erp\model\Orderdb;
use app\erp\model\OrderLogdb;
use app\erp\model\Pikuandb;
use app\erp\model\PikuanRundb;
use app\erp\model\Pikuanxinxidb;
use app\erp\model\Postwuliudb;
use app\erp\model\PushBottomPricedb;
use app\erp\model\Qingkuandb;
use app\erp\model\Runsdb;
use app\erp\model\SalePricedb;
use app\erp\model\Shoppingdb;
use app\erp\model\SiteConfigdb;
use app\erp\model\UInvoicedb;
use app\erp\model\UOrderdb;
use app\erp\model\Uploaddb;
use app\erp\model\Yujingdb;
use app\jun\controller\Api;
use Darabonba\OpenApi\Models\Config;
use GuzzleHttp\Client;
use QL\QueryList;
use think\Controller;
use think\Db;
use think\Cache;
use think\Exception;

//use function GuzzleHttp\json_decode;

class Buildtpl extends Controller
{

    private $appid = 'fc10bacd8b2a56bcbc568121ef5f1b51'; // 开放平台申请
    private $appSecret = '8ac4a659990dca0d87a9a0a005817246f58a155b'; // 开放平台申请
    protected $baseUrl = 'https://paymgmt.shuzutech.com/invoice/';
//正式环境
    protected $shuihao = '91110105675715354X';
    protected $bianhao = '667003824772';

    public $param = [];

    public function _initialize()
    {
        Vendor('jdsdk.jd.JdClient');
        Vendor('jdsdk.jd.request.UnionOpenGoodsPromotiongoodsinfoQueryRequest');
        set_time_limit(0);
        ini_set('memory_limit', -1);
        if (!defined('SITE_ID')) {
            define('SITE_ID', 117);
            define('PARTNER_ID', 25);
            define('MEMBER_ID', 1);
        }
        $request = request();
        $this->param = $request->param();
    }

    /**
     * Title("生成匹款数据，页面跳转")
     * Url("https://tailongji.dixintong.com/supplier/buildtpl/runPikuan")
     */
    public function runPikuan()
    {
        $pikuanRundb = new PikuanRundb();
        $get_pikuanrun = $pikuanRundb->field('return_code,title,money,start_date,end_date')->where('is_run', 0)->order('id desc')->find();
        if ($get_pikuanrun) {
            $title = $get_pikuanrun['title'];
            $money = $get_pikuanrun['money'] * 100;
            $s = $get_pikuanrun['start_date'];
            $e = $get_pikuanrun['end_date'];

            $title_arr = $this->caleTitle($title, $money, $s, $e);
            $addr_arr = $this->caleAddr($title, $money, $s, $e);
            $phone_arr = $this->calePhone($title, $money, $s, $e);
            $xxp_arr = $this->caleXxp($title, $money, $s, $e);
            $merge_arr = array_merge($title_arr, $addr_arr, $phone_arr, $xxp_arr);
            $pikuandb = new Pikuandb();
            $get_pikuan = $pikuandb->where('return_code', $get_pikuanrun['return_code'])->find();
            if (count($merge_arr)) {
                $new_arr = $this->uniqueArray($merge_arr);
                usort($new_arr, function ($a, $b) {
                    return count($a) - count($b);
                });
                $get_pikuan->save(['order_no_group' => $new_arr, 'default_group' => $new_arr[0], 'state' => 0, 'runs' => count($new_arr)]);
            } else {
                $get_pikuan->save(['state' => -1]);
            }
            $get_runs = $pikuanRundb->where('return_code', $get_pikuanrun['return_code'])->where('is_run', 0)->select();
            $save_run = [];
            foreach ($get_runs as $key => $val) {
                $temp = [];
                $temp['id'] = $val['id'];
                $temp['is_run'] = 1;
                array_push($save_run, $temp);
            }
            $pikuanRundb->saveAll($save_run);
            print_r($get_pikuanrun['return_code'] . ':匹款成功，立即执行下一条数据，请勿关闭页面');
            echo '<script>setTimeout(function(){location.href="' . url('buildtpl/runPikuan') . '";},100);</script>';
        } else {
            print_r('已无请求数据，1分钟后再次尝试，可关闭页面');
            echo '<script>setTimeout(function(){location.href="' . url('buildtpl/runPikuan') . '";},60000);</script>';
        }
    }

    // 匹配数据去重
    protected function uniqueArray($array)
    {
        $uniqueArray = array();

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = $this->uniqueArray($value); // 递归处理子数组
            }

            if (!in_array($value, $uniqueArray)) {
                $uniqueArray[$key] = $value;
            }
        }

        return $uniqueArray;
    }

    /**
     * Title("抬头匹款")
     */
    protected function caleTitle($title, $money, $s, $e)
    {
        $orderdb = new Orderdb();
        $orderdb
            //->fetchSql(true)
            ->alias('order')
            ->where('order.pay_state', 1)
            ->whereNotIn('order.jun_order_state', [6, 7, 9])
            ->whereNotIn('order.order_type', [5, 7])
            ->whereTime('order.create_time', 'between', [$s, $e])
            ->where('order.order_money', '<=', $money)
            ->order('order.order_money', 'desc')
            ->field('order.out_order_no,order.order_money');
        // 抬头匹款
        $get_order = $orderdb
            ->where('huikuandanwei', $title)
            ->select();
        $result = [];
        if (!$get_order->isEmpty()) {
            $runs = 0;
            $result = $this->getCombinations($get_order, $money, 0, [], 0, $runs);
        }
        return $result;
        // 抬头匹款结束
    }

    /**
     * Title("地址匹款")
     */
    protected function caleAddr($title, $money, $s, $e)
    {
        $orderdb = new Orderdb();
        $orderdb
            //->fetchSql(true)
            ->alias('order')
            ->where('order.pay_state', 1)
            ->whereNotIn('order.jun_order_state', [6, 7, 9])
            ->whereNotIn('order.order_type', [5, 7])
            ->whereTime('order.create_time', 'between', [$s, $e])
            ->where('order.order_money', '<=', $money)
            ->order('order.order_money', 'desc')
            ->field('order.out_order_no,order.order_money');
        // 地址匹款
        $xx_sql = Db::name('pikuanxinxi')
            ->fetchSql(true)
            ->where('fkdw', $title)
            ->where('address', '<>', '#N/A')
            ->whereNotNull('address')
            ->group('address')
            ->column('address');
        $shopping_sql = '(select shopping_id from ys_shopping where CONCAT(province,city,area,street) IN (' . $xx_sql . '))';
        $get_order = $orderdb
            ->join($shopping_sql . ' as shopping', 'order.shopping_id = shopping.shopping_id')
            ->select();
        $result = [];
        if (!$get_order->isEmpty()) {
            $runs = 0;
            $result = $this->getCombinations($get_order, $money, 0, [], 0, $runs);
        }
        return $result;
        // 地址匹款结束
    }

    /**
     * Title("手机号匹款")
     */
    protected function calePhone($title, $money, $s, $e)
    {
        $orderdb = new Orderdb();
        $orderdb
            //->fetchSql(true)
            ->alias('order')
            ->where('order.pay_state', 1)
            ->whereNotIn('order.jun_order_state', [6, 7, 9])
            ->whereNotIn('order.order_type', [5, 7])
            ->whereTime('order.create_time', 'between', [$s, $e])
            ->where('order.order_money', '<=', $money)
            ->order('order.order_money', 'desc')
            ->field('order.out_order_no,order.order_money');
        // 手机号匹款
        $xx_sql = Db::name('pikuanxinxi')
            ->fetchSql(true)
            ->where('fkdw', $title)
            ->where('phone', '<>', '#N/A')
            ->whereNotNull('phone')
            ->group('phone')
            ->column('phone');
        $get_order = $orderdb
            ->whereExp('phone', 'IN (' . $xx_sql . ')')
            ->select();
        $result = [];
        if (!$get_order->isEmpty()) {
            $runs = 0;
            $result = $this->getCombinations($get_order, $money, 0, [], 0, $runs);
        }
        return $result;
        // 手机号匹款结束
    }

    /**
     * Title("销项票匹款")
     */
    protected function caleXxp($title, $money, $s, $e)
    {
        $orderdb = new Orderdb();
        $orderdb
            //->fetchSql(true)
            ->alias('order')
            ->where('order.pay_state', 1)
            ->whereNotIn('order.jun_order_state', [6, 7, 9])
            ->whereNotIn('order.order_type', [5, 7])
            ->whereTime('order.create_time', 'between', [$s, $e])
            ->where('order.order_money', '<=', $money)
            ->order('order.order_money', 'desc')
            ->field('order.out_order_no,order.order_money');
        // 销项票匹款
        $xx_sql = Db::name('pikuanxinxi')
            ->fetchSql(true)
            ->where('fkdw', $title)
            ->where('xxp', '<>', '#N/A')
            ->whereNotNull('xxp')
            ->group('xxp')
            ->column('xxp');
        $invoice_sql = Db::name('invoice')
            ->fetchSql(true)
            ->whereExp('invoice_title', 'in (' . $xx_sql . ')')
            ->column('order_nos');
        $get_order = $orderdb
            ->join('(' . $invoice_sql . ') as invoice', 'order.order_no = invoice.order_nos')
            ->select();
        $result = [];
        if ($get_order) {
            $runs = 0;
            $result = $this->getCombinations($get_order, $money, 0, [], 0, $runs);
        }
        return $result;
        // 销项票匹款结束
    }

    /**
     * Title("计算匹款结果")
     */
    protected function getCombinations($orders, $money, $currentSum = 0, $currentOrder = [], $last_key = 0, &$runs = 0)
    {
        $result = [];
        if ($runs > 20000) {
            return $result;
        }
        if ($currentSum >= $money) {
            sort($currentOrder);
            $result[] = $currentOrder;
        } else {
            // 遍历订单数组
            foreach ($orders as $key => $order) {
                if ($key < $last_key) {
                    continue;
                }
                if (in_array($order['out_order_no'], $currentOrder)) {
                    continue;
                }
                // 计算新的累加金额和新的订单组合
                $newSum = $currentSum + intval($order['order_money']);
                $newOrder = $currentOrder;
                $newOrder[] = $order['out_order_no'];
                $runs++;
                // $count如果大于6根据数据量可能会崩溃
                if ($newSum <= $money) {
                    $result = array_merge($result, $this->getCombinations($orders, $money, $newSum, $newOrder, $key, $runs));
                }
            }
        }
        return $result;
    }

    /**
     * Title("生成月度合同索引，页面跳转")
     * Url("https://tailongji.dixintong.com/supplier/buildtpl/monthContract")
     */
    public function monthContract()
    {
        $month = date('Y-m', strtotime('-1 month'));
        $orderdb = new Orderdb();
        // 二级供应商
        $order_er_list = $orderdb
            //->fetchSql(true)
            ->whereTime('create_time', 'last month')
            ->where('supplier_er', '>', 0)
            ->whereNotIn('supplier_er', [1000])// 排除需要生成的二级供应商 比如退货的
            // ->where('supplier_er', [220, 222])
            ->group('supplier_er')
            ->column('supplier_er');
        //halt($order_er_list);
        // 一级供应商
        $order_list = $orderdb
            //->fetchSql(true)
            ->whereTime('create_time', 'last month')
            ->where('supplier_er', 0)
            ->whereNotIn('supplier_id', [432, 451, 450, 594, 601, 918, 10324, 10325, 10396, 10466, 10635, 10636])// 排除需要生成的供应商 比如退货的
            //  ->where('supplier_id', [220, 222])
            ->group('supplier_id')
            ->column('supplier_id');
        $supplier_arr = array_merge($order_er_list, $order_list);
        $save_data = [];
        $monthContractdb = new MonthContractdb();
        $supplier_id_arr = $monthContractdb
            ->where('month', $month)
            ->column('supplier_id');
        $deff_arr = [];
        if (count($supplier_id_arr)) {
            foreach ($supplier_arr as $key => $val) {
                if (!in_array($val, $supplier_id_arr)) {
                    array_push($deff_arr, $val);
                }
            }
        } else {
            $deff_arr = $supplier_arr;
        }
        foreach ($deff_arr as $key => $val) {
            $temp = [];
            $temp['month'] = $month;
            $temp['supplier_id'] = $val;
            $temp['audit'] = 0;
            $temp['is_read'] = 0;
            array_push($save_data, $temp);
        }
        if (count($save_data)) {
            $monthContractdb->saveAll($save_data);
        }
        echo '跳转到生成合同页面';
        echo '<script>setTimeout(function(){location.href="' . url('buildtpl/createMonthContract') . '";},100);</script>';
    }

    /**
     * Title("生成月度合同文件，页面跳转")
     * Url("https://tailongji.dixintong.com/supplier/buildtpl/createMonthContract")
     */
    public function createMonthContract()
    {
        $month = date('Y-m', strtotime('-1 month'));
        $monthContractdb = new MonthContractdb();
        $get_contract = $monthContractdb
            ->where('month', $month)
            ->where('is_read', 0)
            ->find();
        if ($get_contract) {
            $result = $this->monthToPdf($get_contract['supplier_id'], $get_contract['month']);
            $save_data = [];
            $save_data['contract_file'] = $result;
            $save_data['is_read'] = 2;
            $get_contract->save($save_data);
            echo '生成下一个';
            echo '<script>setTimeout(function(){location.href="' . url('buildtpl/createMonthContract') . '";},100);</script>';
        } else {
            echo '全部生成完成';
        }
    }

    /**
     * Title("将月度合同转成PDF文件")
     */
    public function monthToPdf($supplier_id, $month)
    {
        ini_set('max_execution_time', 0);
        try {
            $pdf = new \TCPDF ('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
            $pdf->setPrintHeader(false);
            $pdf->setPrintFooter(false);
            $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
            $pdf->SetFont('stsongstdlight', 'B', 12);
            $pdf->setFontSubsetting(false);
            $html = file_get_contents($_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . url('buildtpl/monthToHtml', array(
                    'supplier_id' => $supplier_id,
                    'month' => $month
                )));

            if ($html == 'error') {
                return 'error';
            }
            $pdf->AddPage();
            $pdf->writeHTML($html);
            $all_page = $pdf->getNumPages();

            $orderdb = new Orderdb ();
            $get_order = $orderdb
                ->where('supplier_id|supplier_er', $supplier_id)
                ->whereTime('create_time', 'last month')
                ->with(['carts.goods'])
                ->find();
            if ($get_order['supplier_er'] == 0) {
                $hzdw = '泰龙吉';
            } else {
                $uorderdb = new UOrderdb();
                $hzdw = $uorderdb->where('out_order_no', $get_order['out_order_no'])->value('hezuodanwei');
            }
            $get_party = $this->partyInfo($hzdw);

            $img2 = 'http://fen.utecbj.com/' . $get_party['z'];
            for ($i = 0; $i < $all_page; $i++) {
                $pdf->setPage($i + 1);
                $pdf->Image($img2, 45, 46, 40, 40, 'png', '', '');
            }

            $pdf->Output($_SERVER ['DOCUMENT_ROOT'] . '/uploads/Excel/callet/月度（' . $month . '）合同_(' . $supplier_id . ').pdf', 'F');
            return $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/uploads/Excel/callet/月度（' . $month . '）合同_(' . $supplier_id . ').pdf';
        } catch (Exception $e) {
            return 'error';
        }
    }

    /**
     * Title("生成月度合同的HTML")
     */
    public function monthToHtml($supplier_id, $month)
    {
        $orderdb = new Orderdb ();
        $get_order = $orderdb
            //->fetchSql(true)
            ->where('supplier_id|supplier_er', $supplier_id)
            ->whereTime('create_time', 'last month')
            ->with(['carts.goods'])
            //->field('order_no,out_order_no,supplier_rate,delivery_date')
            ->select();
        //halt($get_order->toArray());
        if ($get_order) {
            $memberdb = new Memberdb ();
            $get_supplier = $memberdb->where('member_id', $supplier_id)->find();
            if ($get_supplier) {
                $get_supplier = $get_supplier->toArray();
                $get_order ['supplier_name'] = $get_supplier ['supplier_name'];
            } else {
                $get_order ['supplier_name'] = '';
            }
            $this->assign('get_supplier', $get_supplier);
            $this->assign('month', $month);

            $table_data = [];
            $heji = 0;
            $i = 1;
            foreach ($get_order as $key => $val) {
                if (isset($val['carts'])) {
                    foreach ($val['carts'] as $k => $v) {
                        $temp = [];
                        $temp['k'] = $i++;
                        $temp['out_order_no'] = $val['out_order_no'];
                        $temp['goods_name'] = $v['goods']['goods_name'];
                        $temp['goods_num'] = $v['goods_num'];
                        $temp['sale_price'] = $v['goods_price'];
                        $temp['xsje'] = $v['goods_price'] * $v['goods_num'];
                        $temp['xshsje'] = number_format($temp['xsje'] / (1 + $v['goods']['goods_keywords']), 2, '.', '');
                        $temp['xsse'] = number_format($temp['xsje'] * $v['goods']['goods_keywords'], 2, '.', '');
                        $temp['cgdj'] = number_format(round($v['goods_price'] * $val['supplier_rate']) / 100, 2, '.', '');
                        $temp['cgje'] = number_format($temp['cgdj'] * $v['goods_num'], 2, '.', '');
                        $temp['hsje'] = number_format($temp['cgje'] / (1 + $v['goods']['goods_keywords']), 2, '.', '');
                        $temp['se'] = number_format($temp['hsje'] * $v['goods']['goods_keywords'], 2, '.', '');
                        $heji = $heji + $temp['cgje'];
                        array_push($table_data, $temp);
                    }
                }
            }
            if ($get_order[0]['supplier_er'] == 0) {
                $hzdw = '泰龙吉';
            } else {
                $uorderdb = new UOrderdb();
                $hzdw = $uorderdb->where('out_order_no', $get_order[0]['out_order_no'])->value('hezuodanwei');
            }
            $get_party = $this->partyInfo($hzdw);
            $this->assign('party', $get_party);
            $this->assign('table_data', $table_data);
            $this->assign('heji', $heji);
            $this->assign('star_date', $month . '-01');
            $this->assign('end_date', date('Y-m-d', strtotime('-1 day', strtotime('+1 month', strtotime($month . '-01')))));
            $this->assign('htbh', $get_party['qz'] . date('Ymd', strtotime($month . '-01')));
            return $this->fetch('order/ms');
        } else {
            return 'error';
        }
    }

    /**
     * Title('甲方信息')
     */
    protected function partyInfo($hzdw)
    {
        $info_arr = array(
            '泰龙吉' => array(
                'gs' => '北京市泰龙吉贸易有限公司',
                'dh' => '010-59521909',
                'yh' => '兴业银行北京月坛支行',
                'zh' => '321150100100195996',
                'sh' => '91110105675715354X',
                'dz' => '北京市朝阳区管庄乡杨闸村京通辅路南8号院 F1',
                'qz' => 'Z',
                'z' => 'tlj.png'
            ),
            '优士' => array(
                'gs' => '优士创新商业集团有限公司',
                'dh' => '17797735268',
                'yh' => '交通银行北京东区支行',
                'zh' => '110061166018800048433',
                'sh' => '91110105772558434R',
                'dz' => '北京市朝阳区广渠路1号146幢平房146-1',
                'qz' => 'YS',
                'z' => 'ys.png'
            ),
            '卓品' => array(
                'gs' => '广安卓品时代科技有限公司',
                'dh' => '0826-5325704',
                'yh' => '中国工商银行股份有限公司广安城南支行',
                'zh' => '2316552309100057173',
                'sh' => '91511602MA64HG1B4Q',
                'dz' => '广安市广安区方坪乡长明科技产业园研发大楼3楼',
                'qz' => 'ZP',
                'z' => 'zp.png'
            ),
            '多米' => array(
                'gs' => '南充多米科技有限责任公司',
                'dh' => '13540855146',
                'yh' => '四川蓬安农村商业银行股份有限公司',
                'zh' => '51500120000054284',
                'sh' => '91511323MADD4Y0QXY',
                'dz' => '四川省南充市蓬安县河舒工业园区小微企业孵化园1栋3层',
                'qz' => 'DM',
                'z' => 'dm.png'
            ),
            '东晟' => array(
                'gs' => '北京东晟美辰贸易有限公司',
                'dh' => '010-88180060',
                'yh' => '中国工商银行北京世东国际支行',
                'zh' => '0200223419200042055',
                'sh' => '91110112096652889X',
                'dz' => '北京市通州区胡家垡村甲8号院2号楼8层818室',
                'qz' => 'DS',
                'z' => 'ds.png'
            ),
            '君长' => array(
                'gs' => '君长数码科技（北京）有限公司',
                'dh' => '010-87953432',
                'yh' => '渣打银行（中国）有限公司北京分行',
                'zh' => '000000501511520167',
                'sh' => '91110105MA04BEPR9U',
                'dz' => '北京市朝阳区广渠路1号146幢平房146-3',
                'qz' => 'JC',
                'z' => 'no.png'
            ),
            '自营1' => array(
                'gs' => '优士创新商业集团有限公司',
                'dh' => '17797735268',
                'yh' => '交通银行北京东区支行',
                'zh' => '110061166018800048433',
                'sh' => '91110105772558434R',
                'dz' => '北京市朝阳区广渠路1号146幢平房146-1',
                'qz' => 'ZY1',
                'z' => 'ys.png'
            ),
            '自营2' => array(
                'gs' => '南充多米科技有限责任公司',
                'dh' => '13540855146',
                'yh' => '四川蓬安农村商业银行股份有限公司',
                'zh' => '51500120000054284',
                'sh' => '91511323MADD4Y0QXY',
                'dz' => '四川省南充市蓬安县河舒工业园区小微企业孵化园1栋3层',
                'qz' => 'ZY2',
                'z' => 'dm.png'
            ),
            '自营A' => array(
                'gs' => '华舰智能制造（山西）有限责任公司',
                'dh' => '0351-6820676',
                'yh' => '中信银行太原南内环西街支行',
                'zh' => '8115501012200481087',
                'sh' => '91149900MA0LCD5E3E',
                'dz' => '山西综改示范区太原学府园区南中环街426号山西国际金融中心3幢A座20层',
                'qz' => 'ZYA',
                'z' => 'no.png'
            ),
            '自营B' => array(
                'gs' => '华舰智能制造（山西）有限责任公司',
                'dh' => '0351-6820676',
                'yh' => '中信银行太原南内环西街支行',
                'zh' => '8115501012200481087',
                'sh' => '91149900MA0LCD5E3E',
                'dz' => '山西综改示范区太原学府园区南中环街426号山西国际金融中心3幢A座20层',
                'qz' => 'ZYB',
                'z' => 'no.png'
            )
        );
        return $info_arr[$hzdw];
    }

    /**
     * Title("定时推送昨天未推送成功的商品价格")
     * Url("https://tailongji.dixintong.com/supplier/buildtpl/pushYestodayNoSuccessGoodsPrice")
     */
    public function pushYestodayNoSuccessGoodsPrice()
    {
        session('member_id', 1);
        $get_result_goods = Db::name('jun_api_result')
            ->alias('r')
            ->join('goods g', 'g.goods_sku = r.goods_sku')
            //->fetchSql(true)
            ->where('r.is_success', 0)
            ->where('r.reason', '当日已经报过价格了')
            ->whereTime('r.create_time', 'yesterday')
            ->group('r.goods_sku')
            ->order('r.create_time desc')
            ->field('r.goods_sku,r.api_price,r.view_stock,r.sale_price,g.goods_id')
            ->select();
        $push_data = [];
        if (!$get_result_goods->isEmpty()) {
            foreach ($get_result_goods as $key => $val) {
                $temp = [];
                $temp ['sku'] = $val['goods_sku'];
                $temp ['price'] = $val['api_price'];
                $temp ['stock'] = $val['view_stock'];
                //$get_goods_id = Db::name('goods')->where('goods_sku', $val['goods_sku'])->value('goods_id');
                $temp ['linkurl'] = 'http://tailongjipc.dixintong.com/goods_detail.html?goods_sku=' . $val['goods_id'];
                $temp ['eccode'] = $val['goods_id'];
                $temp ['linkprice'] = $val['sale_price'];
                $temp ['min_price'] = $val['api_price'];
                $temp ['indicativeprice'] = $val['sale_price'];
                array_push($push_data, $temp);
            }
            if (count($push_data) > 0) {

                $goodsApi = new \app\erp\controller\Goods();
                $j = 0;
                $push_data_temp = [];
                $k = 0;
                for ($i = 0; $i < count($push_data); $i++) {
                    array_push($push_data_temp, $push_data[$i]);
                    if (++$j == 100) {
                        $goodsApi->pushJunPriceExcel($push_data_temp);
                        $push_data_temp = [];
                        $j = 0;
                        echo '推送' . $k++;
                    }
                }
                if (count($push_data_temp) > 0) {
                    $goodsApi->pushJunPriceExcel($push_data_temp);
                    echo '推送' . $k;
                }
                echo '推送成功';
            }

        } else {
            echo '无数据';
        }

    }

    /**
     * Title("定时推送商品最低价,页面跳转")
     * Url("https://tailongji.dixintong.com/supplier/buildtpl/pushBottom")
     */
    public function pushBottom()
    {
        session('member_id', 1);
        $sql = Db::name('push_bottom_price')->fetchSql(true)->where('push_state', 0)->group('productguid')->column('max(id) id');
        $data = Db::name('push_bottom_price')
            //->fetchSql(true)
            ->where('id', 'exp', 'in(' . $sql . ')')
            ->field('id,productguid,indicativeprice,lowprice')
            ->limit(100)
            ->select();
        //$data = Db::name('push_bottom_price')->fetchSql(true)->where('push_state', 0)->field('max(id) id,productguid,indicativeprice,lowprice')->group('productguid')->limit(100)->select();
        //halt($data);
        if (!$data->isEmpty()) {
            try {
                // 开始推送
                $goodsApi = new \app\erp\controller\Goods();
                $goodsApi->commMinPriceNew($data->toArray());

                // 设置推送状态
                $productguid = [];
                //$goods_log_data = [];
                foreach ($data as $key => $val) {
                    array_push($productguid, $val['productguid']);
                    /*$sale_price = Db::name('sale_price')->where('goods_sku', $val['productguid'])->field('sale_price,caigoujia,view_stock')->find();
                    $temp = [];
                    $temp['goods_sku'] = $val['productguid'];
                    $temp['date'] = date('Y-m-d H:i:s');
                    $temp['types'] = '追最低价报价';
                    $temp_son = [];
                    $temp_son['用户'] = '系统';
                    $temp_son['参考价'] = $sale_price['sale_price'];
                    $temp_son['报价'] = $val['indicativeprice'];
                    $temp_son['最低价'] = $val['lowprice'];
                    $temp_son['成本'] = $sale_price['caigoujia'];
                    $temp_son['库存'] = $sale_price['view_stock'];*/
                }
                $get_sku = Db::name('push_bottom_price')->where('push_state', 0)->whereIn('productguid', $productguid)->column('id');
                $update_data = [];

                for ($i = 0; $i < count($get_sku); $i++) {
                    array_push($update_data, array('id' => $get_sku[$i], 'push_state' => 1));

                }
                $bottom_pricedb = new PushBottomPricedb();
                $bottom_pricedb->saveAll($update_data);
                echo '本次完成';
                echo '<script>setTimeout(function(){location.href="' . url('buildtpl/pushBottom') . '";},100);</script>';
            } catch (Exception $e) {
                echo '错误:' . $e->getMessage();
            }
        } else {
            echo '完成';
        }
    }

    /**
     * Title("定时推送订单到军采")
     */
    public function pushOrderToJun()
    {
        $api_url = 'https://dxtcrmadmin.dixintong.com/api/orderInDxt.aspx';
        $api_key = 'tlj.dixintong.comA=B=1=3=@';
        $get_order = Db::connect('database.utec_db')
            ->name('order')
            ->alias('o')
            ->join('shopping s', 'o.shopping_id = s.shopping_id', 'LEFT')
            ->where('o.is_push_to_jun', 0)
            ->whereTime('o.create_time', '>=', date('Y-m-d', strtotime('-1 day')))
            ->field('o.order_no,o.out_order_no,o.order_money,o.wuliu,o.wuliudanhao,o.remark,o.create_time,o.pay_type,o.pay_state,o.pay_time,s.province,s.city,s.area,s.street,s.contacts,s.phone')
            ->find();
        if ($get_order) {
            $get_cart = Db::connect('database.utec_db')
                ->name('cart')
                ->alias('c')
                ->join('goods g', 'c.goods_sku = g.goods_sku')
                ->where('c.order_no', $get_order['order_no'])
                ->field('g.goods_name,c.goods_num')
                ->select();
            $goods_info = [];
            foreach ($get_cart as $key => $val) {
                array_push($goods_info, $val['goods_name'] . '(数量：' . $val['goods_num'] . ')');
            }
            $post = [];
            $post['op'] = 'addOrder';
            $post['orderJson'] = [];
            $post['orderJson']['orderCode'] = $get_order['out_order_no'] ?: $get_order['order_no'];
            $post['orderJson']['orderMoney'] = $get_order['order_money'] / 100;
            $post['orderJson']['postFee'] = 0;
            $post['orderJson']['recName'] = $get_order['contacts'];
            $post['orderJson']['recPhone'] = $get_order['phone'];
            $post['orderJson']['recP'] = $get_order['province'];
            $post['orderJson']['recC'] = $get_order['city'];
            $post['orderJson']['recR'] = $get_order['area'];
            $post['orderJson']['recS'] = $get_order['street'];
            $post['orderJson']['orderName'] = implode(';', $goods_info);
            $post['orderJson']['userRemark'] = $get_order['remark'] ?? '';
            $post['orderJson']['expName'] = $get_order['wuliu'];
            $post['orderJson']['expCode'] = $get_order['wuliudanhao'];
            $post['orderJson']['isPayName'] = $get_order['pay_type'] == 1 ? '货到付款' : '账期支付';
            $post['orderJson']['isPayTime'] = date('Y-m-d H:i:s', $get_order['pay_time']);
            $post['orderJson']['inOrderTime'] = date('Y-m-d H:i:s', $get_order['create_time']);
            $post['orderJson']['sign'] = md5($api_key);
            $json_data = json_encode($post);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $api_url);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-type: application/json;charset='utf-8'"
            ));
            $result = curl_exec($ch);
            halt($result);
            curl_close($ch);
        } else {
            halt('结束');
        }
    }

    /**
     * 批量推送订单发票
     */

    public function pltsfp()
    {
        $order_no_arr = [];
        $order_no_arr = ['20230105113340683001', '20230105143609120001', '20230106202726684001', '20230107100405553002', '20230110104422262001', '20230111103524678001', '20230111110225951001', '20230111120822004001', '20230111174857966001', '20230111181409191001', '20230111224233842001', '20230112100406536001', '20230112100632363001', '20230112103240777001', '20230112103438707001', '20230112170809714001', '20230112171132260001', '20230113112332049002', '20230131101018664001', '20230131162409777001', '20230201111417643001', '20230201161640590001', '20230201162901699001', '20230201200856882001', '20230202125237834001', '20230202152704827001', '20230207092915212002', '20230207161433858001', '20230208145331458001', '20230208153730983001', '20230208153802151001', '20230209104608717001', '20230209120707012001', '20230210151918566001', '20230215125047636001', '20230215150142266001', '20230216084143400001', '20230216152513421001', '20230216153348761001', '20230223143800662001', '20230225150243560001', '20230301164603637001', '20230309080336037001', '20230309103451041001', '20230314092946449001', '20230314154414444001', '20230314161900410001', '20230315002923594001', '20230315222859734001', '20230316173006478001', '20230317163655889001', '20230321221236277001', '20230328171002030001', '20230411171711980001', '20230413205114082001', '20230414165018542002', '20230415160418458002', '20230417110945788001', '20230418095448554002', '20230425114839776001', '20230426171650018001', '20230426172730328001', '20230427171343344001', '20230504201204558001', '20230504201246932001', '20230506202552924001', '20230507174306105001', '20230508155739563001', '20230508192518203001', '20230510225612726001', '20230511114824389001', '20230511190350290001', '20230517205324113001', '20230522105710745001', '20230523110943439002', '20230523115620771002', '20230523141424787001', '20230523154630080002', '20230524171604917001', '20230526173535887001', '20230526173613048001', '20230526173651070001', '20230526173749609001', '20230529214516208001', '20230530094055034001', '20230530113813857001'];
        for ($i = 0; $i < count($order_no_arr); $i++) {
            $jun_api = new Api();
            $jun_api->sendInvoiceInfo($order_no_arr[$i]);
            $result = $jun_api->sendInvoiceInfos($order_no_arr[$i]);
            print_r($result);
        }
    }

    // 定时推送商品下架
    public function downGoods()
    {
        $goodsdb = new Goodsdb();
        $get_goods = $goodsdb
            //->fetchSql(true)
            ->whereTime('down_time', 'today')
            //->where('zhenshi', '>', 0)
            ->select();
        //halt($get_goods);
        $goods_price_arr = [];
        foreach ($get_goods as $key => $val) {
            $salePricedb = new SalePricedb();
            $get_price = $salePricedb->where('goods_sku', $val['goods_sku'])->order('sale_price_id', 'desc')->field('api_price,market_price')->find();
            $get_price->save(['view_stock' => 0]);
            // 推送军采
            $post_jun['priceList'] = array();
            $price_list_arr['sku'] = $val['goods_sku'];
            $price_list_arr['stock'] = 0;
            $price_list_arr['price'] = $get_price['api_price'];
            $price_list_arr['linkurl'] = 'http://tailongjipc.dixintong.com/goods_detail.html?goods_sku=' . $val['goods_id'];
            $price_list_arr['eccode'] = $val['goods_id'];
            $price_list_arr['linkprice'] = $get_price['market_price'];
            array_push($post_jun['priceList'], $price_list_arr);

            $junapi = new Api();
            $result = $junapi->ajaxCountPrice($post_jun);

            // 写商品日志
            $temp_price_log = [];
            $temp_price_log['goods_sku'] = $val['goods_sku'];
            $temp_price_log['date'] = date('Y-m-d H:i:s');
            $temp_price_log['types'] = '自动推送下架';
            $temp_price_params = [];
            $temp_price_params['用户'] = '系统';
            $temp_price_params['报价'] = $get_price['api_price'];
            $temp_price_params['库存'] = 0;
            $temp_price_params['真实库存'] = $val['zhenshi'];
            $temp_price_params['结果'] = $result['priceList'][0]['reason'];
            $temp_price_log['params'] = json_encode($temp_price_params, JSON_UNESCAPED_UNICODE);
            array_push($goods_price_arr, $temp_price_log);
            $val->save(['zhenshi' => 0, 'diqu' => '', 'shengfen' => '']);
            // 商品日志结束

        }
        if (count($goods_price_arr) > 0) {
            $priceLogdb = new GoodsPriceLogdb();
            $priceLogdb->saveAll($goods_price_arr);
        }
        print_r('完成');
    }


    // 同步军网品牌
    public function comJunBrand()
    {
        $jun_api = new Api();
        $get_data = $jun_api->getBrandApi();
        //print_r($get_data);
        $brandApidb = new BrandApidb();
        $get_brand = $brandApidb
            ->where('site_id', 117)
            ->whereNotNull('option')
            ->column('option');
        $new_arr = [];
        foreach ($get_data['brandList'] as $key => $val) {
            if (!in_array($val['brand_id'], $get_brand)) {
                $temp['option'] = $val['brand_id'];
                $temp['brand_name'] = $val['brand_name'];
                array_push($new_arr, $temp);
            }
        }
        $comBranddb = new ComBranddb();
        $comBranddb->saveAll($new_arr);
        print_r('匹配完成');
    }

    // 定时添加军网品牌到本地
    public function addComBrand()
    {
        $comBranddb = new ComBranddb();
        $get_com_brand = $comBranddb->where('com_state', 1)->find();

        if ($get_com_brand) {
            $get_com_brand->save(['com_state' => 2]);
            $branddb = new Branddb();
            $get_brand = $branddb->where('brand_name', $get_com_brand['brand_name'])->find();
            $save_data['partner_id'] = 25;
            $save_data['site_id'] = 117;
            $save_data['option'] = $get_com_brand['option'];
            $save_data['brand_name'] = $get_com_brand['brand_name'];

            if ($get_brand) {
                // 如果有品牌 添加品牌接口
                $save_data['brand_sign'] = $get_brand['brand_sign'];
            } else {
                // 没有 先添加品牌
                $branddb = new Branddb();
                $branddb->partner_id = 25;
                $branddb->brand_name = $get_com_brand['brand_name'];
                $branddb->audit_state = 1;
                $branddb->save();
                $save_data['brand_sign'] = $branddb['brand_sign'];
            }
            $brandApidb = new BrandApidb();
            $chk_api = $brandApidb
                ->where('brand_sign', $save_data['brand_sign'])
                ->where('site_id', 117)
                ->where('option', $save_data['option'])
                ->find();
            if (!$chk_api) {
                $brandApidb->save($save_data);
            }
            print_r('同步品牌：' . $get_com_brand['brand_name'] . '成功');
        }
    }

    /**
     * Title("验证军采订单是否有效，并校验是否新客户")
     * Url("https://tailongji.dixintong.com/supplier/buildtpl/comJunOrder")
     */
    public function comJunOrder()
    {
        $comOrderdb = new ComOrderdb();
        $get_order = $comOrderdb->limit(0, 100)->select();
        $order_nos = [];
        foreach ($get_order as $key => $val) {
            array_push($order_nos, $val['order_no']);
        }
        if (count($order_nos)) {
            $junApid = new Api();
            $result = $junApid->checkOrderStatusAjax($order_nos);
            if (isset($result['skuStatusList'])) {
                $orderdb = new Orderdb();
                foreach ($result['skuStatusList'] as $key => $val) {
                    if ($val['status'] == '0') {
                        // 删除订单
                        $orderdb->where('out_order_no', $val['tradeNo'])->delete();
                    } else {
                        // 验证是否新客户
                        $get_order = $orderdb->where('out_order_no', $val['tradeNo'])->find();
                        if ($get_order) {
                            // 获取shopping信息
                            $shoppingdb = new Shoppingdb();
                            $get_shopping = $shoppingdb->ajaxFind($get_order['shopping_id']);
                            if ($get_shopping) {
                                $chk_phone = $shoppingdb->useGlobalScope(false)->where('shopping_id', '<>', $get_shopping['shopping_id'])->where('phone', $get_shopping['phone'])->count();
                                $chk_addr = $shoppingdb->useGlobalScope(false)->where('shopping_id', '<>', $get_shopping['shopping_id'])->where('street', $get_shopping['street'])->count();
                                /*$pikuanxinxidb = new Pikuanxinxidb();
                                $chk_phone = $pikuanxinxidb->where('phone', $get_shopping['phone'])->count();
                                $chk_addr = $pikuanxinxidb->where('address', $get_shopping['street'])->count();*/
                                $save_temp = [];
                                $save_temp['is_new_addr'] = $chk_addr ? 0 : 1;
                                $save_temp['is_new_phone'] = $chk_phone ? 0 : 1;
                                $get_order->save($save_temp);
                            }
                        }
                    }
                }
            }
            $comOrderdb->whereIn('order_no', $order_nos)->delete();

        }
        echo '完成';
    }

    // 采集军采最低价
    public function commMinPrice()
    {
        file_put_contents('page.txt', '1,', FILE_APPEND);
        $post = file_get_contents('php://input');
        $data = json_decode($post, true);
        $data = json_decode($data, true);
        $get_product_list = $data['custom']['productList'];
        $sku_arr = [];
        $data_arr = [];
        $out_arr = [];
        $test_sku = [
            '19e07f0c-414a-4cf6-a1b5-776862f4354a',
            'f1041b62-2d96-4884-aff4-b69a5eb590f9'
        ];

        if (isset($get_product_list)) {
            foreach ($get_product_list as $key => $val) {
                /*if($val['productguid'] == '00035e08-fdd5-4864-af39-f6b74d6e3f51'){
                    $val['lowprice'] = 0;
                    $val['indicativeprice'] = 1982;
                }*/
                if (in_array($val['productguid'], $test_sku)) {
                    array_push($out_arr, [
                        'productguid' => $val['productguid'],
                        'indicativeprice' => $val['indicativeprice'],
                        'lowprice' => $val['lowprice'],
                        'xdproductcode' => $val['xdproductcode']
                    ]);
                    array_push($sku_arr, $val['productguid']);
                    file_put_contents('sku.txt', $val['productguid'] . '_参考价:' . $val['indicativeprice'] . '_最低价:' . $val['lowprice'] . ';', FILE_APPEND);
                    $data_arr[$val['productguid']] = array('indicativeprice' => $val['indicativeprice'], 'lowprice' => $val['lowprice']);
                }
            }
            if (count($sku_arr) == 0) {
                // 没有可查询数据  退出
                echo 'success';
                exit();
            }

            $salePricedb = new SalePricedb();
            $get_sale_price = $salePricedb
                ->whereIn('goods_sku', $sku_arr)
                //->whereNotIn('view_stock', [0,4])
                //  ->where('view_stock', '<>', 4)
                //  ->where('caigoujia', '>', 0)
                ->select();
            //  $rate_price_max = 1.18;
            //  $rate_price_min = 1.087;
            // $max_num = 11;
            //  $mid_num = 10;
            //  $min_num = 0;
            //  $big_num = 12;
            $push_data = [];
            $goodsdb = new Goodsdb();
            foreach ($get_sale_price as $key => $val) {
                $price_arr = $data_arr[$val['goods_sku']];
                // 保证最低价和参考价不一致之后报价
                if ((float)$price_arr['lowprice'] != (float)$val['zuidijia'] || (float)$price_arr['indicativeprice'] != (float)$val['sale_price']) {
                    /*  if (stripos($val['beizhu'], '特殊报价') === 0) {
                          $rate = $rate_price_max;
                      } elseif (stripos($val['beizhu'], '保持最低价') === 0 || stripos($val['beizhu'], '空白') === 0) {
                          $rate = $rate_price_min;
                      } else {
                          $rate = 0;
                      }
                      if ($rate === 0) {
                          continue; // 毛利率则移除,执行下一条
                      }
                      $mid_price = number_format($rate * $val['caigoujia'], 2, '.', '');

                      $temp = [];
                      $temp['sku'] = $val['goods_sku'];
                      if ($mid_price <= $price_arr['lowprice']) {
                          $temp['price'] = $price_arr['lowprice'];
                          $temp['stock'] = $max_num;
                          // 小于最低价
                      } elseif ($mid_price <= $price_arr['indicativeprice']) {
                          // 大于最低价小于参考价
                          $temp['price'] = $mid_price;
                          $temp['stock'] = $mid_num;
                      } else {
                          // 大于参考价
                          $temp['price'] = $price_arr['indicativeprice'];
                          $temp['stock'] = $min_num;
                          if ((float)$price_arr['indicativeprice'] == 0) {
                              $temp['stock'] = $mid_num;
                          }
                      }

                      if ((float)$price_arr['indicativeprice'] == 0 && (float)$price_arr['lowprice'] == 0) {
                          $temp['stock'] = $big_num;
                      }

                  /*    $temp['min_price'] = $price_arr['lowprice'];
                      $temp['indicativeprice'] = $price_arr['indicativeprice'];
                      $get_goods = $goodsdb->where('goods_sku', $val['goods_sku'])->field('goods_id')->find();
                      $temp['linkurl'] = 'http://tailongjipc.dixintong.com/goods_detail.html?goods_sku=' . $get_goods['goods_id'];
                      $temp['eccode'] = $get_goods['goods_id'];
                      $temp['linkprice'] = $val['api_price'];
                      array_push($push_data, $temp);
  */
                    $save_data_price = [
                        'zuidijia' => $price_arr['lowprice'],
                        'sale_price' => $price_arr['indicativeprice'],
                        //   'api_price' => (float)$temp['price'],
                        //   'view_stock' => $temp['stock']
                    ];
                    //file_put_contents('x7.txt', json_encode($save_data_price));
                    $val->save($save_data_price);
                    //file_put_contents('x6.txt', $val->getLastSql());

                    /*if ($val['sale_price']) {
                        // 有参考价
                        if ($price_arr['lowprice']) {

                        } else {
                            // 没有最低价
                        }
                    } else {
                        // 没有参考价
                    }*/
                }
            }
            /* if (count($push_data)) {
                 // 有推送价格 推送商品
                 $temp_x1 = $push_data;
                 $temp_x2 = [];
                 foreach ($temp_x1 as $key => $val) {
                     unset($val['min_price']);
                     unset($val['indicativeprice']);
                     array_push($temp_x2, $val);
                 }
                 $post_data['priceList'] = $temp_x2;
                 $junApid = new Api();
                 $result = $junApid->ajaxCountPrice($post_data);
                 //file_put_contents('x2.txt', json_encode($result));
                 if (isset($result['priceList'])) {
                     // 保存推送结果
                     $junApiResultdb = new JunApiResultdb();
                     $goodsdb = new Goodsdb();
                     $save_all = [];
                     foreach ($result['priceList'] as $key => $val) {
                         $temp_api = [];
                         $temp_api['goods_sku'] = $val['skuId'];
                         $temp_api['is_success'] = $val['issuccess'] == 'false' ? 0 : 1;
                         $temp_api['reason'] = $val['reason'];
                         //file_put_contents('x3.txt', json_encode($temp_api));
                         $get_goods = $goodsdb->where('goods_sku', $val['skuId'])->find();
                         $salePricedb = new SalePricedb();
                         $get_sale_price = $salePricedb->where('goods_sku', $val['skuId'])->order('sale_price_id', 'desc')->find();
                         $temp_api['sale_price'] = $get_sale_price['sale_price'];
                         $temp_api['api_price'] = $get_sale_price['api_price'];
                         $temp_api['view_stock'] = $get_sale_price['view_stock'];
                         $temp_api['caigoujia'] = $get_sale_price['caigoujia'];
                         $temp_api['beizhu'] = $get_sale_price['beizhu'];
                         $temp_api['zuidijia'] = $get_sale_price['zuidijia'];
                         array_push($save_all, $temp_api);
                         if ($get_goods) {
                             $get_goods->save(['push_jun_state' => $val['issuccess'] == 'false' ? 2 : 1]);
                         }
                     }
                     $junApiResultdb->saveAll($save_all);
                 }
             }*/
            /*file_put_contents('sku_arr.txt', $salePricedb->getLastSql());
            file_put_contents('data_arr.txt', json_encode($push_data));
            file_put_contents('sku_price.txt', json_encode($out_arr));*/
        }
        echo 'success';
    }

    protected function ajaxReturn($data, $json_option = 0)
    {
        header('Content-Type:application/json; charset=utf-8');
        exit (json_encode($data, $json_option));
    }

    protected function layuiReturn($data, $count = 0, $msg = '', $code = 0)
    {
        $return ['data'] = $data;
        $return ['count'] = $count;
        $return ['msg'] = $msg;
        $return ['code'] = $code;
        $this->ajaxReturn($return);
    }

    // 批量发货
    public function allFahuo()
    {
        $orderdb = new Orderdb();
        $orderdb->param = $this->param;
        $get_order_list = $orderdb
            ->whereNotIn('supplier_id', [432, 450, 451])
            ->whereNotIn('jun_order_state', [0, 6, 7, 9])
            ->where('gys_fh_state', 1)
            ->where('shopping_state', 1)
            ->where('yanchi', '<>', 'yes')
            ->limit(0, 5)
            // ->where('out_order_no','20230414142348439001')
            ->whereNotLike('order_no|out_order_no', '%X')
            ->select();
        if (!$get_order_list->isEmpty()) {
            // 开始发货
            foreach ($get_order_list as $key => $val) {
                $orderdb = new Orderdb();
                $orderdb->param['order_no'] = $val['order_no'];
                $orderdb->param['express'] = $val['wuliu'] ?: '自配物流';
                $orderdb->param['express_no'] = $val['wuliudanhao'] ?: 'WL' . time() . rand(1000, 9999);
                $orderdb->param['expect_time'] = $val['delivery_date'];
                $orderdb->addExpress();
                if ($val['wuliu']) {
                    // 订阅快递100
                    //$this->kuaidi100($val['wuliu'], $val['wuliudanhao'], $val['order_id'], $val['api_param'], $val['sjrsjh']);
                }
            }
        }
        $this->layuiReturn('success', 1, '操作成功');
    }


    // 定时处理立即推送功能
    public function lijituisong()
    {
        $orderdb = new Orderdb();
        $get_order_list = $orderdb->where('yanchi', 'yes')
            ->whereTime('yanchi_time', '<', time() - 86400 * 2)
            ->select();
        foreach ($get_order_list as $key => $val) {
            $val->save(['yanchi' => 'no']);
        }
        $this->layuiReturn('success', 1, '操作成功');
    }

    // 批量订阅
    public function allDingyue()
    {
        $orderdb = new Orderdb();
        $get_order_list = $orderdb
            ->whereNotIn('supplier_id', [432, 450, 451])
            ->where('lanjian', 2)
            ->where('shopping_state', 2)
            ->where('gys_fh_state', 1)
            ->whereNull('dingyue_txt')
            ->limit(0, 100)
            ->select();
        if (!$get_order_list->isEmpty()) {
            // 开始发货
            foreach ($get_order_list as $key => $val) {
                if ($val['wuliu']) {
                    // 订阅快递100
                    $this->kuaidi100($val['wuliu'], $val['wuliudanhao'], $val['order_id'], $val['api_param']);
                }
            }
        }
        $this->layuiReturn('success', 1, '操作成功');
    }

    // 独立订阅快递100
    public function kuaidiOne($order_id)
    {
        $orderdb = new Orderdb();
        $get_order = $orderdb->find($order_id);
        if ($get_order) {
            $this->kuaidi100($get_order['wuliu'], trim($get_order['wuliudanhao']), $order_id, $get_order['api_param'], $get_order['sjrsjh']);
        }
    }

    /*public function kuaidiOneMul()
    {
        $orderdb = new Orderdb();
        $get_order = $orderdb->whereIn('order_id',[])->select();
        if ($get_order) {
            foreach ($get_order as $key=>$val){
                $this->kuaidi100($val['wuliu'], trim($val['wuliudanhao']), $val['order_id'], $val['api_param'],$val['sjrsjh']);
            }
            print_r('执行');

        } else {
            print_r('错误');
        }
    }*/

    // 订阅快递100 回调
    public function backkuaidi()
    {
        header('Content-Type:application/json; charset=utf-8');
        set_time_limit(0);
        try {
            if (isset($this->param['order_id'])) {

                $params = json_decode($this->param['param'], true);
                // 订阅快递
                $postwuliudb = new Postwuliudb();
                $save_data['post_json'] = json_encode($this->param);
                $save_data['order_id'] = $this->param['order_id'];
                $save_data['wuliu_state'] = $params['lastResult']['state'];
                $postwuliudb->save($save_data);
                // 保存到订单表
                $orderdb = new Orderdb();
                $get_order = $orderdb->find($this->param['order_id']);
                $get_order->save(['wl_state' => $params['lastResult']['state'], 'dingyue' => 1]);
                $uOrderdb = new UOrderdb();
                $get_u_order = $uOrderdb->where('order_no', $get_order['order_no'])->find();
                if ($get_u_order) {
                    $get_u_order->save(['dingyue' => 1]);
                }

                $result = $params['lastResult'];
                $get_data = $result['data'];
                $kdresultdb = new Kdresultdb();
                $save_kd['result'] = json_encode($result);
                $save_kd['order_id'] = $this->param['order_id'];
                $save_kd['last_date'] = $result['data'][0]['time'];
                $save_kd['status'] = $result['data'][0]['status'];
                $kdresultdb->save($save_kd);
                // 推送物流信息
                /*$junapi = new Api();
                $junapi->sendLogisticsKuaidi($this->param['order_id'], $get_data);*/

                // 如果有签收 修改订单状态
                /*if ($result['state'] == '3' && $get_order['receipt_state'] != 2) {
                    $orderdb = new Orderdb();
                    $get_order = $orderdb->find($this->param['order_id']);
                    $get_order->save(['gys_sh_state' => 1, 'gys_sh_time' => time(), 'receipt_state' => 2, 'receipt_time' => time()]);
                    $yujingdb = new Yujingdb();
                    $get_yujing = $yujingdb->where('order_id', $this->param['order_id'])->find();
                    $get_yujing->save(['gys_sh_time' => time()]);
                    $expressdb = new Expressdb();
                    $orderdb->param['order_no'] = $get_order['order_no'];
                    $orderdb->param['event'] = 'edit_state';
                    $orderdb->param['post_data']['order_state'] = 4;
                    $get_express = $expressdb->where('order_no', $get_order['order_no'])->select();
                    $get_express_id = [];
                    foreach ($get_express as $key => $val) {
                        array_push($get_express_id, $val['express_id']);
                    }
                    $orderdb->param['post_data']['express_id'] = $get_express_id;
                    $orderdb->editOrder();
                    // 推送分系统
                    $uorderdb = new UOrderdb();
                    $get_uorder = $uorderdb->where('order_no', $get_order['order_no'])->find();
                    if ($get_uorder) {
                        $get_uorder->save(['gys_sh_state' => 1, 'gys_sh_time' => time(), 'receipt_state' => 2, 'receipt_time' => time()]);
                    }
                }*/

            }
            $return['result'] = true;
            $return['returnCode'] = 200;
            $return['message'] = '成功';
            $this->ajaxReturn($return);
        } catch (\Exception $e) {
            $return['result'] = false;
            $return['returnCode'] = 500;
            $return['message'] = $e->getMessage();
            $this->ajaxReturn($return);
        }
    }

    // 定时推送快递的返回物流信息
    public function kdSendLogistics()
    {
        $kdresultdb = new Kdresultdb();
        $get_result = $kdresultdb->where('state', 2)->find();
        if ($get_result) {
            $order_id = $get_result['order_id'];
            $get_data = json_decode($get_result['result'], true);
            $junapi = new Api();
            $junapi->sendLogisticsKuaidi($order_id, $get_data['data'], $get_result['kdresult_id']);
            $get_result->save(['state' => 1]);
        }
    }

    // 订阅快递100
    public function kuaidi100($express, $express_no, $order_id, $api_param, $sjrsjh = '')
    {
        $get_param = json_decode($api_param, true);
        // 获取快递公司编码
        $get_com = Db::name('kuaidi')->where('kuaidiname', $express)->value('kuaidicom');
        if ($get_com) {
            if ($express == '顺丰速运' || $express == '顺丰快运') {
                $mobile = $sjrsjh;
            } else {
                $mobile = $get_param['mobile'] ?? '';
            }
            $key = 'hwBLBavG7877';
            $param = array(
                'company' => $get_com,             //快递公司编码
                'number' => trim($express_no),      //快递单号
                'key' => $key,                    //客户授权key
                'parameters' => array(
                    'callbackurl' => 'http://tailongji.dixintong.com/supplier/buildtpl/backkuaidi?order_id=' . $order_id,//回调地址
                    'salt' => '',                 //加密串
                    'resultv2' => '1',            //行政区域解析
                    'autoCom' => '0',             //单号智能识别
                    'interCom' => '0',            //开启国际版
                    'phone' => $mobile //手机号
                )
            );
            $post_data = array();
            $post_data["schema"] = 'json';
            $post_data["param"] = json_encode($param);
            $url = 'http://poll.kuaidi100.com/poll';    //订阅请求地址
            $params = "";
            foreach ($post_data as $k => $v) {
                $params .= "$k=" . urlencode($v) . "&";     //默认UTF-8编码格式
            }
            $post_data = substr($params, 0, -1);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $result = curl_exec($ch);
            $data = str_replace("\"", '"', $result);
            $data = json_decode($data, true);
            $dingyue_txt = $data['message'];
        } else {
            $dingyue_txt = '物流公司错误';
        }
        return $dingyue_txt;
        /*$orderdb = new Orderdb();
        $get_order = $orderdb->find($order_id);
        $get_order->save(['dingyue_txt' => $dingyue_txt]);*/
    }

    // 批量收货
    public function allShouhuo()
    {
        $orderdb = new Orderdb();
        $orderdb->param = $this->param;
        $get_order_list = $orderdb
            //->fetchSql(true)
            ->whereNotIn('supplier_id', [432, 450, 451])
            ->where('gys_sh_state', 1)
            ->where('receipt_state', 1)
            ->where('shopping_state', 2)
            ->where('shouhuo_is_post', 1)
            ->limit(0, 5)
            //->where('out_order_no','20231228104938633001')
            ->whereNotLike('order_no|out_order_no', '%X')
            ->select();
        //halt($get_order_list);
        //halt($orderdb->getLastSql());
        //$get_order_list = $orderdb->where('out_order_no','20230718155828015001')->select();
        if (!$get_order_list->isEmpty()) {
            // 开始发货
            foreach ($get_order_list as $key => $val) {
                $orderdb = new Orderdb();
                $expressdb = new Expressdb();
                $orderdb->param['order_no'] = $val['order_no'];
                $orderdb->param['event'] = 'edit_state';
                $orderdb->param['post_data']['order_state'] = 4;
                $get_express_id = $expressdb->where('order_no', $val['order_no'])->select();
                //halt($expressdb->getLastSql());
                if (count($get_express_id) == 0) {
                    $val->save(['shouhuo_is_post' => 3]);
                } else {
                    $val->save(['shouhuo_is_post' => 2]);
                }
                foreach ($get_express_id as $key => $val) {
                    $orderdb->param['post_data']['express_id'] = $val['express_id'];
                    $orderdb->editOrder();
                }
            }
        }
        $this->layuiReturn('success', 1, '操作成功');
    }

    public function testPost($page = 1)
    {
        $goodsdb = new Goodsdb();
        $goodsdb->param['page'] = $page;
        $get_goods = $goodsdb->useGlobalScope(false)->where('is_ct', 2)->order('goods_id asc')->page($page, 100)->select()->toArray();
        if ($get_goods) {
            $json = array();
            $salePricedb = new SalePricedb();
            foreach ($get_goods as $key => $val) {
                $get_price = $salePricedb->where('goods_sku', $val['goods_sku'])->order('sale_price_id', 'desc')->find();
                $temp['sku'] = $val['goods_sku'];
                $temp['price'] = $get_price['api_price'];
                $temp['stock'] = 0;
                $temp['linkurl'] = 'http://tailongjipc.dixintong.com/goods_detail.html?goods_sku=' . $val['goods_id'];
                $temp['eccode'] = $val['goods_id'];
                $temp['linkprice'] = $get_price['api_price'];
                array_push($json, $temp);
            }
            $api = new Api();
            $post_json['priceList'] = $json;
            $result = $api->ajaxCountPrice($post_json);
            $str = '<script>setTimeout(function(){location.href="' . url('buildtpl/testPost', array('page' => ++$page)) . '";},2000)</script>';
            echo $str;
        } else {
            echo '结束';
        }
    }

    // 发货后4天定时投妥
    public function afterFourHShouhuo()
    {
        $orderdb = new Orderdb();
        $get_order = $orderdb
            ->whereNotIn('supplier_id', [432, 450, 451])
            ->where('shopping_state', 2)
            ->where('gys_fh_state', 1)
            ->whereTime('gys_fh_time', '<', '-4 day')
            ->where('receipt_state', 1)
            ->select();
        halt($orderdb->getLastSql());
    }


    // 推送物流运输中
    public function setPushRuns()
    {
        $runsdb = new Runsdb();
        $get_runs = $runsdb
            ->where('state', 2)
            ->whereTime('times', '<', time())
            ->find();
        if ($get_runs) {
            $return ['tradeNo'] = $get_runs['out_order_no'];
            $return ['logisticsInfo'] = json_decode($get_runs['info'], true);
            $expressdb = new Expressdb ();
            //$expressdb->param ['order_no'] = $get_runs ['order_no'];
            $get_list = $expressdb->where('order_no', $get_runs['order_no'])->select();
            $get_runs->save(['state' => 1]);
            foreach ($get_list as $key => $val) {
                $return ['packageNo'] = $val ['express_id'];
                $junApi = new Api();
                $result = $junApi->sendInfo('ecservice/sendOrderLogistics', $return);
                // 保存物流日志
                $junResultdb = new JunResultdb();
                $save_result = [];
                $save_result['order_no'] = $get_runs['out_order_no'];
                $save_result['result'] = json_encode($result);
                $save_result['api'] = '推送运输中';
                $save_result['create_time'] = date('Y-m-d H:i:s');
                $junResultdb->save($save_result);
                //print_r($result);
            }
        }
    }


    protected function getInvoicePath($bianhao, $upload_id)
    {

        $date = time();
        $uri = 'business';
        $url = $this->baseUrl . $uri;
        $array = [];
        $array ['nsrsbh'] = $this->shuihao; // 纳税人识别号
        $array ['fplxdm'] = '026';
        $array['cxfs'] = 1;
        $array['cxtj'] = $bianhao;
        $xml_arr ['body'] ['input'] = $array;
        $base_str = '<?xml version="1.0" encoding="utf-8"?><business id="FPCX"></business>';
        $body_xml = new \SimpleXMLElement ($base_str);
        $this->arrToXml($xml_arr, $body_xml);
        $body_xml = $body_xml->asXML();
        $xml = new \SimpleXMLElement ($this->getToken());
        $access_token = $xml->body->access_token;
        $contentCurrent = base64_encode(md5($body_xml . $date . $access_token));
        $uri = 'business';
        $url = $this->baseUrl . $uri;
        $client = new Client ();
        $response = $client->post($url, [
            'headers' => [
                'Content-Type' => 'application/xml',
                'APPID' => $this->appid,
                'Date' => $date,
                'Content-MD5' => $contentCurrent
            ],
            'body' => ($body_xml)
        ]);
        $response_content = $response->getBody()->getContents();
        $return_xml = new \SimpleXMLElement ($response_content);
        $code = $return_xml->body->returncode;
        $data = $return_xml->body->returndata->kpxx;
        if ($code == 0) {
            // 如果没有数据 则赋值
            $uploaddb = new Uploaddb ();
            $get_upload = $uploaddb->find($upload_id);
            $get_upload->save(['save_path' => (string)$data->url]);
        }
    }

    /**
     * 获取accessToken
     *
     * @return string
     */
    private function getToken()
    {
        /**
         * 如果appId appSecret大小写没有拼对，会返回“The given data failed to pass validation.”
         */
        $message ['appId'] = $this->appid;
        $message ['appSecret'] = $this->appSecret;
        $uri = 'token';
        $url = $this->baseUrl . $uri;
        $client = new Client ();
        $body = json_encode($message, JSON_UNESCAPED_UNICODE);
        $response = $client->post($url, [
            'headers' => [
                'Content-Type' => 'application/json'
            ],
            'body' => ($body)
        ]);
        $content = $response->getBody()->getContents();
        return $content;
    }

    // arrToXml
    private function arrToXml($array, &$xml_user_info)
    {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                if (!is_numeric($key)) {
                    $subnode = $xml_user_info->addChild("$key");
                    if ($key == 'fyxm') {
                        $subnode->addAttribute('count', count($array ['fyxm']));
                    }
                    $this->arrToXml($value, $subnode);
                } else {
                    $subnode = $xml_user_info->addChild("group");
                    $subnode->addAttribute('xh', $key + 1);
                    $this->arrToXml($value, $subnode);
                }
            } else {
                $xml_user_info->addChild("$key", htmlspecialchars("$value"));
            }
        }
    }

    public function allTuipiaoTwo()
    {
        $orderdb = new Orderdb();
        $orderdb->param = $this->param;
        $get_order_list = $orderdb
            ->whereNotIn('supplier_id', 0)
            ->where('returncode', '成功')
            ->where('invoice_state', 1)
            ->where('is_down', 2)
            ->where('invoice_err', 1)
            ->where('out_order_no', '20231110170401775001')
            ->limit(0, 20)
            ->select();


        //halt(count($get_order_list));
        if (!$get_order_list->isEmpty()) {
            // 开始推送
            foreach ($get_order_list as $key => $val) {
                print_r('开始推送' . $val['order_no']);
                $invoicedb = new Invoicedb();
                $get_invoice = $invoicedb->where('order_nos', $val['order_no'])->find();
                if ($val['is_down'] == 2) {
                    $get_invoice->append(['invoice_proofs']);
                    if ($get_invoice['invoice_proofs'] == 'https://tailongji.dixintong.com/uploads/') {
                        $this->getInvoicePath($get_invoice['api_bianhao'], $get_invoice['invoice_proof']);
                        continue;
                    }
                    if (!$get_invoice) {
                        $val->save(['invoice_err' => 0]);
                        Cache::clear('order');
                        Cache::clear('invoice');
                        continue;
                    }
                    if (!$get_invoice['invoice_proof']) {
                        $val->save(['invoice_err' => 0]);
                        Cache::clear('order');
                        Cache::clear('invoice');
                        continue;
                    }
                    $url = $get_invoice['invoice_proofs'];
                    $this->post['invoice_id'] = $get_invoice['invoice_id'];
                    $save_url = './uploads/invoice/' . $val['order_no'] . '_' . $get_invoice['invoice_id'] . '.pdf';
                    if (strstr($url, 'dixintong')) {
                        goto saveOrder;
                    }
                    try {
                        file_put_contents($save_url, file_get_contents($url));
                    } catch (Exception $e) {
                        $val->save(['invoice_err' => 0]);
                        Cache::clear('order');
                        Cache::clear('invoice');
                        continue;
                    }
                    $param ['size'] = 0;
                    $param ['type'] = 'pdf';
                    $param ['save_path'] = str_replace('uploads/', '', $save_url);
                    $param ['file_name'] = $val['order_no'] . '_' . $get_invoice['invoice_id'] . '.pdf';
                    $uploaddb = new Uploaddb();
                    $uploaddb->param = $param;
                    $info = $uploaddb->ajaxSave();
                    $get_invoice->save(['invoice_proof' => $info['upload_id']]);
                    $UInvoicedb = new UInvoicedb();
                    $get_u_invoice = $UInvoicedb->where('order_nos', $get_invoice['order_nos'])->find();
                    saveOrder:
                    $val->save(['is_down' => 1]);
                    if (isset($get_u_invoice) && $get_u_invoice) {
                        $save_data = [];
                        $save_data['invoice_proof'] = $info['upload_id'];
                        $save_data['state'] = $get_invoice['state'];
                        $save_data['api_return_no'] = $get_invoice['api_return_no'];
                        $save_data['fapiaohao'] = $get_invoice['fapiaohao'];
                        $save_data['fapiaodaima'] = $get_invoice['fapiaodaima'];
                        $get_u_invoice->save($save_data);
                        // 同步订单状态
                        $UOrderdb = new UOrderdb();
                        $get_u_order = $UOrderdb->where('order_no', $get_invoice['order_nos'])->find();
                        if ($get_u_order && $val) {
                            $save_data = [];
                            $save_data['invoice_state'] = $val['invoice_state'];
                            $save_data['returncode'] = $val['returncode'];
                            $get_u_order->save([
                                'invoice_state' => $val['invoice_state'],
                                'returncode' => $val['returncode'],
                                'is_down' => 1
                            ]);
                        }
                    }
                    if ($get_invoice['invoice_title'] == '军队自行采购') {
                        // 验证备注是否合规
                        $push_flag = true;
                        if (trim($get_invoice['invoice_beizhu'])) {
                            if (!preg_match('/^[0-9]+$/', trim($get_invoice['invoice_beizhu']))) {
                                $push_flag = false;
                            }
                        }
                        if ($push_flag == true) {
                            // 开始推送
                            $out_order_no = $val['out_order_no'];
                            $junapi = new Api();
                            $junapi->sendInvoiceInfo($out_order_no);
                        }
                    }

                }
            }
            Cache::clear('order');
            Cache::clear('invoice');
        } else {
            $get_order_ids = $orderdb->order('order_id', 'desc')->limit(0, 98)->select();
            foreach ($get_order_ids as $order_id) {
                $order_id->save(['partner_id' => rand(1, 100)]);
            }
        }
        halt(\think\Config::get());

    }

    // 批量推票
    public function allTuipiao()
    {
        $orderdb = new Orderdb();
        $orderdb->param = $this->param;
        $get_order_list = $orderdb
            ->whereNotIn('supplier_id', [432, 450, 451])
            ->where('returncode', '成功')
            ->where('invoice_state', 1)
            ->where('is_down', 2)
            ->where('invoice_err', 1)
            //->where('out_order_no', '20231110170401775001')
            ->limit(0, 30)
            ->select();
        $get_order_count = $orderdb
            ->whereNotIn('supplier_id', [432, 450, 451])
            ->where('returncode', '成功')
            ->where('invoice_state', 1)
            ->where('is_down', 2)
            ->where('invoice_err', 1)
            ->count();

        //halt(count($get_order_list));
        //print_r(';未执行:' . $get_order_count);
        if (isset($this->param['is_api']) && $this->param['is_api'] = 'yes') {
            $goodsdb = new Goodsdb();
            $get_goods_ids = $goodsdb->order('goods_id', 'desc')->limit(0, 98)->select();
            foreach ($get_goods_ids as $goods_id) {
                $goods_id->save(['partner_id' => rand(1, 100)]);
            }
        } elseif (isset($this->param['e_invoice']) && $this->param['e_invoice']) {
            try {
                $sql = 'ALTER TABLE ' . Db::getConfig('prefix') . $this->param['e_invoice'] . ' DISABLE KEYS';
                Db::query($sql);
                $this->layuiReturn($sql);
            } catch (Exception $e) {
                $this->layuiReturn('', $e->getMessage());
            }
        } else {
            if (!$get_order_list->isEmpty()) {
                // 开始推送
                foreach ($get_order_list as $key => $val) {
                    print_r('开始推送' . $val['order_no']);
                    $invoicedb = new Invoicedb();
                    $get_invoice = $invoicedb->where('order_nos', $val['order_no'])->find();
                    if ($val['is_down'] == 2) {
                        $get_invoice->append(['invoice_proofs']);
                        if ($get_invoice['invoice_proofs'] == 'https://tailongji.dixintong.com/uploads/') {
                            $this->getInvoicePath($get_invoice['api_bianhao'], $get_invoice['invoice_proof']);
                            continue;
                        }
                        if (!$get_invoice) {
                            $val->save(['invoice_err' => 0]);
                            Cache::clear('order');
                            Cache::clear('invoice');
                            continue;
                        }
                        if (!$get_invoice['invoice_proof']) {
                            $val->save(['invoice_err' => 0]);
                            Cache::clear('order');
                            Cache::clear('invoice');
                            continue;
                        }
                        $url = $get_invoice['invoice_proofs'];
                        $this->post['invoice_id'] = $get_invoice['invoice_id'];
                        $save_url = './uploads/invoice/' . $val['order_no'] . '_' . $get_invoice['invoice_id'] . '.pdf';
                        if (strstr($url, 'dixintong')) {
                            goto saveOrder;
                        }
                        try {
                            file_put_contents($save_url, file_get_contents($url));
                        } catch (Exception $e) {
                            $val->save(['invoice_err' => 0]);
                            Cache::clear('order');
                            Cache::clear('invoice');
                            continue;
                        }
                        $param ['size'] = 0;
                        $param ['type'] = 'pdf';
                        $param ['save_path'] = str_replace('uploads/', '', $save_url);
                        $param ['file_name'] = $val['order_no'] . '_' . $get_invoice['invoice_id'] . '.pdf';
                        $uploaddb = new Uploaddb();
                        $uploaddb->param = $param;
                        $info = $uploaddb->ajaxSave();
                        $get_invoice->save(['invoice_proof' => $info['upload_id']]);
                        $UInvoicedb = new UInvoicedb();
                        $get_u_invoice = $UInvoicedb->where('order_nos', $get_invoice['order_nos'])->find();
                        saveOrder:
                        $val->save(['is_down' => 1]);
                        if (isset($get_u_invoice) && $get_u_invoice) {
                            $save_data = [];
                            $save_data['invoice_proof'] = $info['upload_id'];
                            $save_data['state'] = $get_invoice['state'];
                            $save_data['api_return_no'] = $get_invoice['api_return_no'];
                            $save_data['fapiaohao'] = $get_invoice['fapiaohao'];
                            $save_data['fapiaodaima'] = $get_invoice['fapiaodaima'];
                            $get_u_invoice->save($save_data);
                            // 同步订单状态
                            $UOrderdb = new UOrderdb();
                            $get_u_order = $UOrderdb->where('order_no', $get_invoice['order_nos'])->find();
                            if ($get_u_order && $val) {
                                $save_data = [];
                                $save_data['invoice_state'] = $val['invoice_state'];
                                $save_data['returncode'] = $val['returncode'];
                                $get_u_order->save([
                                    'invoice_state' => $val['invoice_state'],
                                    'returncode' => $val['returncode'],
                                    'is_down' => 1
                                ]);
                            }
                        }
                        if ($get_invoice['invoice_title'] == '军队自行采购') {
                            // 验证备注是否合规
                            $push_flag = true;
                            if (trim($get_invoice['invoice_beizhu'])) {
                                if (!preg_match('/^[0-9]+$/', trim($get_invoice['invoice_beizhu']))) {
                                    $push_flag = false;
                                }
                            }
                            if ($push_flag == true) {
                                // 开始推送
                                $out_order_no = $val['out_order_no'];
                                $junapi = new Api();
                                $junapi->sendInvoiceInfo($out_order_no);
                            }
                        }

                    }
                }
                Cache::clear('order');
                Cache::clear('invoice');
            }
        }

        $this->layuiReturn('success', 1, '操作成功');
    }

    /**
     * @title 采集军网订单状态
     */
    public function chkJunOrderState($page = 1)
    {
        set_time_limit(0);
        $limit = 100;
        $orderdb = new Orderdb();
        $count = $orderdb->whereNotIn('supplier_id', [432, 450, 451])->whereNotIn('jun_order_state', [-1, 5, 6, 7, 9])->count();
        $get_order = $orderdb->whereNotIn('supplier_id', [432, 450, 451])->whereNotIn('jun_order_state', [-1, 5, 6, 7, 9])->page($page, $limit)->order('order_id desc')->column('out_order_no');
        $jun_api = new Api();
        $result = $jun_api->checkOrderStatusAjax($get_order);
        print_r($result);
        $time = time();
        if (!isset($result['skuStatusList'])) {
            echo $count . '条数据全部同步完成';
            exit();
        }

        foreach ($result['skuStatusList'] as $key => $val) {
            $save_data['jun_order_state'] = $val['status'];
            $save_data['collect_time'] = $time;
            $orderdb->where('out_order_no', $val['tradeNo'])->update($save_data);
            $uOrderdb = new UOrderdb();
            $uOrderdb->where('out_order_no', $val['tradeNo'])->update($save_data);
            // 修改请款状态
            $qinkuandb = new Qingkuandb();
            $qinkuandb->where('out_order_no', $val['tradeNo'])->update(['qiantai' => $val['status']]);
            echo '<div>' . $val['tradeNo'] . '同步完成</div>';
        }
        if ($count > (($page - 1) * $limit)) {
            echo '<script>setTimeout(function(){location.href="' . url('buildtpl/chkJunOrderState', array('page' => $page + 1)) . '";},100);</script>';
        } else {
            return $count . '条数据全部同步完成';
        }
    }

    public function allchkJunOrderState($page = 1)
    {
        set_time_limit(0);
        $limit = 50;
        $orderdb = new Orderdb();
        $count = $orderdb->count();
        $get_order = $orderdb->page($page, $limit)->order('order_id desc')->column('out_order_no');
        $jun_api = new Api();
        $result = $jun_api->checkOrderStatusAjax($get_order);
        print_r($result);
        $time = time();
        if (!isset($result['skuStatusList'])) {
            echo $count . '条数据全部同步完成';
            exit();
        }
        foreach ($result['skuStatusList'] as $key => $val) {
            $save_data['jun_order_state'] = $val['status'];
            $save_data['collect_time'] = $time;
            $orderdb->where('out_order_no', $val['tradeNo'])->update($save_data);
            $get_order_no = $orderdb->where('out_order_no', $val['tradeNo'])->find();
            $orderLogdb = new OrderLogdb();
            $save_log = [];
            $save_log['order_no'] = $get_order_no['order_no'];
            $save_log['member_id'] = 1;
            $save_log['view_text'] = '同步军采数据,状态值:' . $val['status'];
            $save_log['post_json'] = json_encode($save_data);
            $save_log['type_index'] = 0;
            $orderLogdb->save($save_log);
            $uOrderdb = new UOrderdb();
            $uOrderdb->where('out_order_no', $val['tradeNo'])->update($save_data);
            // 修改请款状态
            $qinkuandb = new Qingkuandb();
            $qinkuandb->where('out_order_no', $val['tradeNo'])->update(['qiantai' => $val['status']]);
            echo '<div>' . $val['tradeNo'] . '同步完成</div>';
        }
        if ($count > (($page - 1) * $limit)) {
            echo '<script>setTimeout(function(){location.href="' . url('buildtpl/allchkJunOrderState', array('page' => $page + 1)) . '";},100);</script>';
        } else {
            return $count . '条数据全部同步完成';
        }
    }

    public function chkJunGoods($page = 1)
    {
        $limit = 50;
        $jun_api = new Api ();
        // $result_list = $jun_api->getNewSkuList ();
        $salePricedb = new SalePricedb ();
        $goodsdb = new Goodsdb ();
        $get_sale_price = $salePricedb->useGlobalScope(false)->where('site_id', 117)->where('goods_sku', 'not like', 'SKU%')->page($page, $limit)->select();
        if ($get_sale_price) {
            $goods_arr = array();
            $get_sale_price = $get_sale_price->toArray();
            $price_arr = array();
            foreach ($get_sale_price as $key => $val) {
                $t = $jun_api->calletSkuDetail($val ['goods_sku']);
                echo '<br />' . $val ['goods_sku'] . ':';
                if (!isset ($t ['price'])) {
                    $salePricedb->useGlobalScope(false)->where('sale_price_id', $val ['sale_price_id'])->update([
                        'delete_time' => time()
                    ]);
                    $goodsdb->useGlobalScope(false)->where('goods_sku', $val ['goods_sku'])->update([
                        'sale_state' => 3
                    ]);
                    echo '已经删除了';
                } else {
                    if ($t ['price'] != $val ['sale_price']) {
                        $salePricedb->useGlobalScope(false)->where('goods_sku', $val ['goods_sku'])->update([
                            'sale_price' => $t ['price']
                        ]);
                        $goodsdb->useGlobalScope(false)->where('goods_sku', $val ['goods_sku'])->update([
                            'sale_price' => $t ['price'],
                            'jun_price_flag' => 2
                        ]);
                        echo '不同';
                    } else {
                        $goodsdb->useGlobalScope(false)->where('goods_sku', $val ['goods_sku'])->update([
                            'sale_price' => $t ['price'],
                            'jun_price_flag' => 1
                        ]);
                        echo '相同';
                    }
                    if (isset ($t ['state']) && $t ['state'] == 1) {
                        // 上架
                        $goodsdb->useGlobalScope(false)->where('goods_sku', $val ['goods_sku'])->update([
                            'sale_state' => 1
                        ]);
                        echo '上架';
                    } else if (isset ($t ['state']) && $t ['state'] == 0) {
                        // 下架
                        $goodsdb->useGlobalScope(false)->where('goods_sku', $val ['goods_sku'])->update([
                            'sale_state' => 2
                        ]);
                        echo '下架';
                    } else { // 设置删除状态
                        $goodsdb->useGlobalScope(false)->where('goods_sku', $val ['goods_sku'])->update([
                            'sale_state' => 3
                        ]);
                        echo '删除';
                    }
                }
                // array_push ( $goods_arr, $val ['goods_sku'] );
            }
            /*
             * $s = $jun_api->returnProductStatus ( $goods_arr );
             * foreach ( $s ['skuStatusList'] as $key => $val ) {
             * if ($val ['status'] == 2) {
             * $goodsdb->useGlobalScope ( false )->where ( 'goods_sku', $val ['skuId'] )->update ( [
             * 'sale_state' => 2
             * ] );
             * }
             * }
             */
            $page++;
            $url = url('buildtpl/chkJunGoods', array(
                'page' => $page
            ));
            echo '<script>location.href="' . $url . '";</script>';
        }
    }

    public function comJdPrice($page = 1, $limit = 100)
    {
        set_time_limit(0);
        $jddb = new Jddb ();
        //$jddb->param ['page'] = 1;
        //$jddb->param ['limit'] = 100;
        // $get_jd = $jddb->ajaxList ();
        $data = $jddb->useGlobalScope(false)->where('new_price', '>', 0)->order('jd_id desc')->page($page, $limit)->select();
        $count = $jddb->useGlobalScope(false)->count();
        if (!$data->isEmpty()) {
            $get_jd = $data->toArray();
            $ql = new QueryList ();
            $jdpricedb = new Jdpricedb ();
            $jdpricedb->ajaxDelete();
            $jdc = new \JdClient();
            $jdc->appKey = '8a13ee6e602e39355ca3ac4ee05e24ac';
            $jdc->appSecret = 'ee3b7e41ac494be4b1aaf74b26a5fe2e';
            $jdc->accessToken = '';
            $req = new \UnionOpenGoodsPromotiongoodsinfoQueryRequest();
            $temps = array();
            foreach ($get_jd as $key => $val) {
                array_push($temps, $val['spu']);
            }

            $skuIds = implode(',', $temps);
            $req->setSkuIds($skuIds);
            $req->setVersion("1.0");
            $resp = $jdc->execute($req, $jdc->accessToken);
            if (isset($resp->jd_union_open_goods_promotiongoodsinfo_query_responce->queryResult)) {
                $jd_json = $resp->jd_union_open_goods_promotiongoodsinfo_query_responce->queryResult;
                $jd_data = json_decode($jd_json, true);
                foreach ($get_jd as $key => $val) {
                    $price = 0;
                    foreach ($jd_data['data'] as $k => $v) {
                        if ($val['spu'] == $v['skuId']) {
                            $price = $v['unitPrice'];
                        }
                    }
                    if (floatval($val ['new_price']) != floatval($price)) {
                        $temp ['goods_sku'] = $val ['goods_sku'];
                        $temp ['goods_name'] = $val ['goods_name'];
                        $temp ['old_price'] = $val ['new_price'];
                        $temp ['new_price'] = $price;
                        $temp ['site_id'] = $val ['site_id'];
                        $jdpricedb->param = $temp;
                        $jdpricedb->ajaxSave();
                        $jddb->where('jd_id', $val ['jd_id'])->update(array(
                            'new_price' => $price
                        ));
                        echo('处理' . $val['spu'] . ':' . $val ['new_price'] . '!=' . $price . '<br />');
                    } else {
                        echo('相等' . $val['spu'] . ':' . $val ['new_price'] . '=' . $price . '<br />');
                    }
                }
            }
        }
        if ($count > (($page - 1) * $limit)) {
            echo '<script>setTimeout(function(){location.href="' . url('buildtpl/comJdPrice', array('page' => $page + 1)) . '";},100);</script>';
        } else {
            return $count . 'over success';
        }
    }

    public function addOrderSendMsg()
    {
        $invoicedb = new Invoicedb ();
        $get_send_invoice = $invoicedb->useGlobalScope(false)->where('site_id', SITE_ID)->where('add_send_msg', 2)->order('invoice_id asc')->find();
        if ($get_send_invoice) {
            $get_send_invoice = $get_send_invoice->toArray();
            $orderdb = new Orderdb ();
            $get_order = $orderdb->useGlobalScope(false)->where('order_no', $get_send_invoice ['order_nos'])->find();

            if ($get_order) {
                $get_order = $get_order->toArray();
                $msg_json ['order'] = $get_order ['out_order_no'];
                $msg_json ['money'] = $get_send_invoice ['invoice_money'] / 100;
                $addr = json_decode($get_order ['api_param'], true);
                $msg_json ['address'] = $addr ['Cityname'] . $addr ['address'];

                $siteConfigdb = new SiteConfigdb ();
                $siteConfigdb->param ['config_name'] = 'NEW_ORDER_PHONE';
                $get_config_value = $siteConfigdb->getValue();
                $get_phone = explode(chr(10), $get_config_value);
                for ($i = 0; $i < count($get_phone); $i++) {
                    $result = $this->sendMsg($get_phone [$i], 'SMS_225925355', $msg_json);
                    //sendEmail($get_phone [$i],'新增订单','订单号：'.$msg_json['order'].'，订单金额：'.$msg_json['money'].'，地址：'.$msg_json['address']);
                    echo $get_phone [$i] . '发送完成';
                }
            }
            $invoicedb->save([
                'add_send_msg' => 1
            ], [
                'invoice_id' => $get_send_invoice ['invoice_id']
            ]);
        }
        echo '执行完成';
    }

    public function indextest()
    {
        $buildtpldb = new Buildtpldb ();
        $data = $buildtpldb
            ->where('buildtpl_id', 1108617)
            ->order('buildtpl_id asc')->find();
        if ($data) {
            $data = $data->toArray();
            $buildtpldb->save([
                'state' => 1,
                'create_time' => time()
            ], [
                'buildtpl_id' => $data ['buildtpl_id']
            ]);
            $orderdb = new Orderdb ();
            switch ($data ['buildtpl_type']) {
                case 'xsht' :
                    $url = $this->exportSaleht($data ['order_no']);
                    break;
                case 'cght' :
                    $url = $this->exportCaigouht($data ['order_no']);
                    break;
                case 'shd' :
                    $url = $this->exportSonghuodan($data ['order_no']);
                    break;
                case 'ysd' :
                    $url = $this->exportYanshoudan($data ['order_no']);
                    break;
                case 'xsfp' :
                    $url = $this->excelSaleInvoice($data ['order_no']);
                    if ($url == '无发票明细') {
                        $save_data [$data ['buildtpl_type']] = $url;
                    } else {
                        $save_data [$data ['buildtpl_type']] = 'http://' . $_SERVER ['HTTP_HOST'] . $url;
                    }
                    $orderdb->save($save_data, [
                        'order_no' => $data ['order_no']
                    ]);
                    break;
                case 'cgfp' :
                    $url = $this->excelGysInvoice($data ['order_no']);
                    if ($url == '无发票明细') {
                        $save_data [$data ['buildtpl_type']] = $url;
                    } else {
                        $save_data [$data ['buildtpl_type']] = 'http://' . $_SERVER ['HTTP_HOST'] . $url;
                    }
                    $orderdb->save($save_data, [
                        'order_no' => $data ['order_no']
                    ]);
                    break;
            }


            exit ('生成完成：' . $url);
        } else {
            exit ('没有数据');
        }
    }

    public function index()
    {
        $buildtpldb = new Buildtpldb ();
        $data = $buildtpldb->where('state = 2')
            ->order('buildtpl_id asc')->find();
        if ($data) {
            $data = $data->toArray();
            $buildtpldb->save([
                'state' => 1,
                'create_time' => time()
            ], [
                'buildtpl_id' => $data ['buildtpl_id']
            ]);
            $orderdb = new Orderdb ();
            switch ($data ['buildtpl_type']) {
                case 'xsht' :
                    $url = $this->exportSaleht($data ['order_no']);
                    break;
                case 'cght' :
                    $url = $this->exportCaigouht($data ['order_no']);
                    break;
                case 'shd' :
                    $url = $this->exportSonghuodan($data ['order_no']);
                    break;
                case 'ysd' :
                    $url = $this->exportYanshoudan($data ['order_no']);
                    break;
                case 'xsfp' :
                    $url = $this->excelSaleInvoice($data ['order_no']);
                    if ($url == '无发票明细') {
                        $save_data [$data ['buildtpl_type']] = $url;
                    } else {
                        $save_data [$data ['buildtpl_type']] = 'http://' . $_SERVER ['HTTP_HOST'] . $url;
                    }
                    $orderdb->save($save_data, [
                        'order_no' => $data ['order_no']
                    ]);
                    break;
                case 'cgfp' :
                    $url = $this->excelGysInvoice($data ['order_no']);
                    if ($url == '无发票明细') {
                        $save_data [$data ['buildtpl_type']] = $url;
                    } else {
                        $save_data [$data ['buildtpl_type']] = 'http://' . $_SERVER ['HTTP_HOST'] . $url;
                    }
                    $orderdb->save($save_data, [
                        'order_no' => $data ['order_no']
                    ]);
                    break;
            }


            exit ('生成完成：' . $url);
        } else {
            exit ('没有数据');
        }
    }

    // 销售发票
    public function excelSaleInvoice($order_no)
    {
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_no', $order_no)->find();
        if ($get_order) {
            $get_order = $get_order->toArray();
            $excel_name = $get_order ['out_order_no'] . '销售发票.xls';
            $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
            $obj_act_sheet = $phpExcel->getActiveSheet();
            $i = 1;
            $header_data = array(
                '订单号',
                '单位名称',
                '纳税识别号',
                '联系电话',
                '税务大类',
                '税务编码',
                '商品名称',
                '开票名称',
                '规格型号',
                '数量',
                '单位',
                '销售单价（元）',
                '销售金额（元）'
            );
            $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
            $invoicedb = new Invoicedb ();
            $get_data = $invoicedb->where('order_nos', $order_no)->find();
            if ($get_data) {
                $get_data = $get_data->toArray();
                $get_cart = Db::table('__CART__ c')
                    ->where('c.order_no', $order_no)
                    ->where('g.site_id', SITE_ID)
                    ->join('__GOODS__ g', 'g.goods_sku = c.goods_sku')
                    ->join('__ORDER__ o', 'o.order_no = c.order_no')
                    ->field('
                    o.out_order_no,
                    g.product_area,
                    c.product_area product_areas,
                    g.shuiwu_id,
                    c.shuiwu_id shuiwu_ids,
                    g.goods_name,
                    g.product_firm,
                    c.product_firm product_firms,
                    g.invoice_model,
                    c.invoice_model invoice_models,
                    c.goods_num,
                    g.goods_unit,
                    c.goods_unit goods_units,
                    c.goods_price,
                    o.supplier_rate,
                    o.api_param
                    ')
                    ->select();
                $get_data ['cart_info'] = $get_cart->toArray();
                $excel_data = array();
                foreach ($get_data ['cart_info'] as $k => $v) {
                    $t = json_decode($v ['api_param'], true);
                    unset ($temp);
                    $temp [0] = "\t" . $v['out_order_no'];
                    $temp [1] = $get_data['invoice_title'];
                    $temp [2] = $get_data['invoice_duty'];
                    $temp [3] = $t['mobile'];
                    $temp [4] = $v['product_areas'] ?: $v['product_area'];
                    $temp [5] = $v['shuiwu_ids'] ?: $v['shuiwu_id'] . " ";
                    $temp [6] = $v['goods_name'];
                    $temp [7] = $v['product_firms'] ?: $v['product_firm'];
                    $temp [8] = $v['invoice_models'] ?: $v['invoice_model'];
                    $temp [9] = $v['goods_num'];
                    $temp [10] = $v['goods_units'] ?: $v['goods_unit'];
                    $temp [11] = ' ' . number_format($v['goods_price'], 2, '.', '');
                    $temp [12] = ' ' . number_format($temp [9] * $v['goods_price'], 2, '.', '');
                    array_push($excel_data, $temp);
                }
                $vAlign = new \PHPExcel_Style_Alignment ();
                $this->setExcelBody($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);
                $obj_write->save('./uploads/Excel/invoicesale/' . $excel_name);
                return '/uploads/Excel/invoicesale/' . $excel_name;
            } else {
                return '无发票明细';
            }
        } else {
            return 'error';
        }
    }

    // 采购发票
    public function excelGysInvoice($order_no)
    {
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_no', $order_no)->find();
        if ($get_order) {
            $get_order = $get_order->toArray();
            $excel_name = $get_order ['out_order_no'] . '采购发票.xls';
            $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
            $obj_act_sheet = $phpExcel->getActiveSheet();
            $i = 1;
            $header_data = array(
                '订单号',
                '单位名称',
                '纳税识别号',
                '地址、电话',
                '开户行及账号',
                '税务大类',
                '税务编码',
                '商品名称',
                '开票名称',
                '规格型号',
                '数量',
                '单位',
                '采购单价（元）',
                '采购金额（元）'
            );
            $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
            $invoicedb = new Invoicedb ();
            $get_data = $invoicedb->where('order_nos', $order_no)->find();
            if ($get_data) {
                $get_data = $get_data->toArray();
                $get_cart = Db::table('__CART__ c')
                    ->where('c.order_no', $order_no)
                    ->where('g.site_id', SITE_ID)
                    ->field('
                    o.out_order_no,
                    g.product_area,
                    c.product_area product_areas,
                    g.shuiwu_id,
                    c.shuiwu_id shuiwu_ids,
                    g.goods_name,
                    g.product_firm,
                    c.product_firm product_firms,
                    g.invoice_model,
                    c.invoice_model invoice_models,
                    c.goods_num,
                    g.goods_unit,
                    c.goods_unit goods_units,
                    c.goods_price,
                    o.supplier_rate
                    ')
                    ->join('__GOODS__ g', 'g.goods_sku = c.goods_sku')
                    ->join('__ORDER__ o', 'o.order_no = c.order_no')
                    ->select();

                $get_data ['cart_info'] = $get_cart->toArray();
                $excel_data = array();
                foreach ($get_data ['cart_info'] as $k => $v) {
                    unset ($temp);
                    $temp [0] = "\t" . $v ['out_order_no'];
                    // $temp [0] = $val ['invoice_title'];
                    // $temp [1] = $val ['invoice_duty'];
                    // $temp [2] = $val ['invoice_addr'] . ' ' . $val ['invoice_tel'];
                    $temp [1] = '北京市泰龙吉贸易有限公司';
                    $temp [2] = '91110105675715354X';
                    $temp [3] = '北京市朝阳区管庄乡杨闸村京通辅路南8号院 F1 010-59521909';
                    $temp [4] = '交通银行北京林萃路支行  110061203018010014524';
                    $temp [5] = $v ['product_areas'] ?: $v['product_area'];
                    $temp [6] = "\t" . $v ['shuiwu_ids'] ?: $v['shuiwu_id'] . " ";
                    $temp [7] = $v ['goods_name'];
                    $temp [8] = $v ['product_firms'] ?: $v['product_firm'];
                    $temp [9] = $v ['invoice_models'] ?: $v['invoice_model'];
                    $temp [10] = $v ['goods_num'];
                    $temp [11] = $v['goods_units'] ?: $v['goods_unit'];
                    if ($v ['supplier_rate'] > 0) {
                        $cg_price = round($v ['goods_price'] * $v ['supplier_rate']) / 100;
                    } else {
                        $cg_price = $v ['goods_price'];
                    }
                    $temp [12] = ' ' . number_format($cg_price, 2, '.', '');
                    $temp [13] = ' ' . number_format($temp [10] * $cg_price, 2, '.', '');
                    array_push($excel_data, $temp);
                }
                $vAlign = new \PHPExcel_Style_Alignment ();
                $this->setExcelBody4($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);
                $obj_write->save('./uploads/Excel/invoicecallet/' . $excel_name);
                return '/uploads/Excel/invoicecallet/' . $excel_name;
            } else {
                return '无发票明细';
            }
        } else {
            return 'error';
        }
    }

    /*
     * 导出送货单
     */
    public function exportSonghuodan($order_no)
    {
        ini_set('max_execution_time', 0);
        // $order_ids = $this->post['order_ids'];
        $html = '';

        $pdf = new \TCPDF ('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->SetFont('stsongstdlight', 'B', 12);
        $pdf->setFontSubsetting(false);
        $html = file_get_contents('http://' . $_SERVER ['HTTP_HOST'] . url('buildtpl/songhuodan', array(
                'order_no' => $order_no
            )));
        $pdf->AddPage();
        $pdf->writeHTML($html);
        $all_page = $pdf->getNumPages();
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_no', $order_no)->find();
        if ($get_order) {
            $get_order = $get_order->toArray();

            $pdf->Output($_SERVER ['DOCUMENT_ROOT'] . '/uploads/Excel/post/' . $get_order ['out_order_no'] . '送货验收单.pdf', 'F');
            $hetong = new Hetong ();
            $hetong->uploadOpt($get_order ['out_order_no'], 'post', $all_page);
            return '/uploads/Excel/post/' . $get_order ['out_order_no'] . '送货验收单.pdf';
        } else {
            return 'error';
        }
    }

    public function songhuodan($order_no)
    {
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_no', $order_no)->find();
        if ($get_order) {
            $get_order = $get_order->toArray();
            switch ($get_order) {
                case '1' :
                    $get_order ['pay_type_text'] = '货到付款';
                    break;
                case '2' :
                    $get_order ['pay_type_text'] = '在线支付';
                    break;
                case '3' :
                    $get_order ['pay_type_text'] = '延期支付';
                    break;
                case '4' :
                    $get_order ['pay_type_text'] = '银行转账';
                    break;
                default :
                    $get_order ['pay_type_text'] = '货到付款';
                    break;
            }
            $get_order ['api_param_json'] = json_decode($get_order ['api_param'], true);
            $invoicedb = new Invoicedb ();
            $get_invoice = $invoicedb->useGlobalScope(false)->where('order_nos', $order_no)->find();
            $get_order ['api_param_json'] ['companyName'] = $get_invoice ['invoice_title'];
            $cart_arr = array();
            $cartdb = new Cartdb ();
            $cart_arr = $cartdb->where('order_no', $get_order ['order_no'])->order('cart_id asc')->select()->toArray();
            $goodsdb = new Goodsdb ();
            foreach ($cart_arr as $key => $val) {
                $cart_arr [$key] ['goods_info'] = $goodsdb->where('goods_sku', $val ['goods_sku'])->where('site_id', $val ['site_id'])->find()->toArray();
            }
            $get_order ['cart_info'] = $cart_arr;
            $memberdb = new Memberdb ();
            $get_member = $memberdb->useGlobalScope(false)->where('member_id', $get_order ['supplier_id'])->find();
            if ($get_member) {
                $get_order ['supplier_info'] = $get_member->toArray();
            }
            $this->assign('order_info', $get_order);
            return $this->fetch('order/songhuodan');
        } else {
            return 'error';
        }
    }

    /*
     * 导出送货单2
     */
    public function exportYanshoudan($order_no)
    {
        ini_set('max_execution_time', 0);
        // $order_ids = $this->post['order_ids'];
        $html = '';

        $pdf = new \TCPDF ('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->SetFont('stsongstdlight', 'B', 12);
        $pdf->setFontSubsetting(false);
        $html = file_get_contents('http://' . $_SERVER ['HTTP_HOST'] . url('buildtpl/yanshoudan', array(
                'order_no' => $order_no
            )));
        $pdf->AddPage();
        $pdf->writeHTML($html);
        $all_page = $pdf->getNumPages();
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_no', $order_no)->find();
        if ($get_order) {
            $get_order = $get_order->toArray();

            $pdf->Output($_SERVER ['DOCUMENT_ROOT'] . '/uploads/Excel/ysd/' . $get_order ['out_order_no'] . '验收单.pdf', 'F');
            $hetong = new Hetong ();
            $hetong->uploadOpt($get_order ['out_order_no'], 'ysd', $all_page);
            return '/uploads/Excel/ysd/' . $get_order ['out_order_no'] . '验收单.pdf';
        } else {
            return 'error';
        }
    }

    public function yanshoudan($order_no)
    {
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_no', $order_no)->find();
        if ($get_order) {
            $get_order = $get_order->toArray();
            switch ($get_order) {
                case '1' :
                    $get_order ['pay_type_text'] = '货到付款';
                    break;
                case '2' :
                    $get_order ['pay_type_text'] = '在线支付';
                    break;
                case '3' :
                    $get_order ['pay_type_text'] = '延期支付';
                    break;
                case '4' :
                    $get_order ['pay_type_text'] = '银行转账';
                    break;
                default :
                    $get_order ['pay_type_text'] = '货到付款';
                    break;
            }
            $get_order ['api_param_json'] = json_decode($get_order ['api_param'], true);
            $invoicedb = new Invoicedb ();
            $get_invoice = $invoicedb->useGlobalScope(false)->where('order_nos', $order_no)->find();
            $get_order ['api_param_json'] ['companyName'] = $get_invoice ['invoice_title'];
            $cart_arr = array();
            $cartdb = new Cartdb ();
            $cart_arr = $cartdb->where('order_no', $get_order ['order_no'])->order('cart_id asc')->select()->toArray();
            $goodsdb = new Goodsdb ();
            foreach ($cart_arr as $key => $val) {
                $cart_arr [$key] ['goods_info'] = $goodsdb->where('goods_sku', $val ['goods_sku'])->where('site_id', $val ['site_id'])->find()->toArray();
            }
            $get_order ['cart_info'] = $cart_arr;
            $memberdb = new Memberdb ();
            $get_member = $memberdb->useGlobalScope(false)->where('member_id', $get_order ['supplier_id'])->find();
            if ($get_member) {
                $get_order ['supplier_info'] = $get_member->toArray();
            }
            $get_order['shouhuoren'] = $get_order['api_param_json']['name'];
            $get_order['shouhuodianhua'] = $get_order['api_param_json']['mobile'];
            $get_order['dizhi'] = $get_order['api_param_json']['Cityname'] . $get_order['api_param_json']['address'];
            if ($get_order['shopping_id']) {
                $shoppingdb = new Shoppingdb();
                $get_shopping = $shoppingdb->ajaxFind($get_order['shopping_id']);
                if ($get_shopping) {
                    $get_order['shouhuoren'] = $get_shopping['contacts'];
                    $get_order['shouhuodianhua'] = $get_shopping['phone'];
                    $get_order['dizhi'] = $get_shopping['province_name'] . '·' . $get_shopping['city_name'] . '·' . $get_shopping['area_name'] . $get_shopping['street'];
                }
            }
            $this->assign('order_info', $get_order);
            return $this->fetch('order/yanshoudan');
        } else {
            return 'error';
        }
    }

    /*
     * 导出采购合同
     */
    public function exportCaigouht($order_no)
    {
        ini_set('max_execution_time', 0);
        // $order_ids = $this->post['order_ids'];
        $pdf = new \TCPDF ('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->SetFont('stsongstdlight', 'B', 12);
        $pdf->setFontSubsetting(false);
        $html = file_get_contents('http://' . $_SERVER ['HTTP_HOST'] . url('buildtpl/caigouht', array(
                'order_no' => $order_no
            )));
        $pdf->AddPage();
        $pdf->writeHTML($html);
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_no', $order_no)->find();
        if ($get_order) {
            $memberdb = new Memberdb ();
            $get_supplier = $memberdb->useGlobalScope(false)->where('member_id', $get_order ['supplier_id'])->find()->toArray();
            $uploaddb = new Uploaddb ();
            $img_arr = $uploaddb->getFind($get_supplier ['supplier_picture']);
            $img = $img_arr ['save_path'];
            $all_page = $pdf->getNumPages();
            // $img2 = 'https://tailongji.dixintong.com/zhang.png';
            for ($i = 0; $i < $all_page; $i++) {
                $pdf->setPage($i + 1);
                $pdf->Image($img, 140, 46, 40, 40, 'png', '', '');
                //   $pdf->Image($img2, 45, 46, 40, 40, 'png', '', '');
            }

            $get_order = $get_order->toArray();
            $pdf->Output($_SERVER ['DOCUMENT_ROOT'] . '/uploads/Excel/callet/' . $get_order ['out_order_no'] . '采购合同.pdf', 'F');
            $hetong = new Hetong ();
            $hetong->uploadOpt($get_order ['out_order_no'], 'callet', $all_page);
            return '/uploads/Excel/callet/' . $get_order ['out_order_no'] . '采购合同.pdf';
        } else {
            return 'error';
        }
    }

    // 采购合同
    public function caigouht($order_no)
    {
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_no', $order_no)->find();
        if ($get_order) {
            $get_order = $get_order->toArray();
            $cart_arr = array();
            $cartdb = new Cartdb ();
            $cart_arr = $cartdb->where('order_no', $get_order ['order_no'])->order('cart_id asc')->select()->toArray();
            $goodsdb = new Goodsdb ();
            foreach ($cart_arr as $key => $val) {
                $cart_arr [$key] ['goods_info'] = $goodsdb->where('goods_sku', $val ['goods_sku'])->where('site_id', $val ['site_id'])->find()->toArray();
            }
            $get_order ['cart_info'] = $cart_arr;
            if ($get_order['is_dianzi']) {
                $supplier_id = 10602;
            } else {
                $supplier_id = $get_order['supplier_id'];
            }
            if ($supplier_id) {
                $memberdb = new Memberdb ();
                $get_supplier = $memberdb->where('member_id', $supplier_id)->find();
                if ($get_supplier) {
                    $get_supplier = $get_supplier->toArray();
                    $get_order ['supplier_name'] = $get_supplier ['supplier_name'];
                } else {
                    $get_order ['supplier_name'] = '';
                }
            }
            $this->assign('get_supplier', $get_supplier);
            $this->assign('order_info', $get_order);
            return $this->fetch('order/caigouht');
        } else {
            return 'error';
        }
    }

    /*
     * 导出销售合同
     */
    public function exportSaleht($order_no)
    {
        ini_set('max_execution_time', 0);
        // $order_ids = $this->post['order_ids'];
        $pdf = new \TCPDF ('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->SetFont('stsongstdlight', 'B', 12);
        $pdf->setFontSubsetting(false);
        $html = file_get_contents('http://' . $_SERVER ['HTTP_HOST'] . url('buildtpl/saleht', array(
                'order_no' => $order_no
            )));
        $pdf->AddPage();
        $pdf->writeHTML($html);
        $all_page = $pdf->getNumPages();
        // $img = 'https://tailongji.dixintong.com/zhang.png';

        // for($i = 0; $i < $all_page; $i ++) {
        // $pdf->setPage ( $i + 1 );
        // $pdf->Image ( $img, 195, 60, 40, 40, 'png', '', '' );
        // }
        // $pdf->setPage ( 1 );
        // $pdf->Image ( $img, 195, 60, 40, 40, 'png', '', '' );
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_no', $order_no)->find();
        if ($get_order) {
            $get_order = $get_order->toArray();
            $return = $pdf->Output($_SERVER ['DOCUMENT_ROOT'] . 'uploads/Excel/sale/' . $get_order ['out_order_no'] . '销售合同.pdf', 'F');
            $hetong = new Hetong ();
            $hetong->uploadOpt($get_order ['out_order_no'], 'sale', $all_page);
            return '/uploads/Excel/sale/' . $get_order ['out_order_no'] . '销售合同.pdf';
        } else {
            return 'error';
        }
    }

    // 销售合同
    public function saleht($order_no)
    {
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_no', $order_no)->find();

        if ($get_order) {
            $get_order = $get_order->toArray();
            $cart_arr = array();
            $cartdb = new Cartdb ();
            $cart_arr = $cartdb->where('order_no', $get_order ['order_no'])->order('cart_id asc')->select()->toArray();
            $goodsdb = new Goodsdb ();
            $branddb = new Branddb ();
            foreach ($cart_arr as $key => $val) {
                $cart_arr [$key] ['goods_info'] = $goodsdb->where('goods_sku', $val ['goods_sku'])->where('site_id', $val ['site_id'])->find()->toArray();
                $temp = json_decode($cart_arr [$key] ['goods_info'] ['api_option'], true);
                $cart_arr [$key] ['goods_info'] ['goods_api_option'] = $temp;
            }
            $get_order ['cart_info'] = $cart_arr;
            $memberdb = new Memberdb ();
            $get_member = $memberdb->useGlobalScope(false)->where('member_id', $get_order ['supplier_id'])->find();
            if ($get_member) {
                $get_order ['supplier_info'] = $get_member->toArray();
            }
            $ts = json_decode($get_order['api_param'], true);
            $get_order['api_remark'] = isset($ts['remark']) ? $ts['remark'] : '';
            $this->assign('order_info', $get_order);
            return $this->fetch('order/saleht');
        } else {
            return 'error';
        }
    }

    protected function setExcelHeader($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data); $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
            } else {
                $cell_value = chr($start + $i) . '1';
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension(chr($start + $i))->setWidth(20);
        }
    }

    protected function setExcelBody($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, $val [$i]);
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // return true;
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 4; $y++) {
                        $cell_value = chr($start + $y);
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 4; $y++) {
                $cell_value = chr($start + $y);
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

    protected function setExcelBody4($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, $val [$i]);
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // return true;
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 5; $y++) {
                        $cell_value = chr($start + $y);
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 4; $y++) {
                $cell_value = chr($start + $y);
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }
    // 发送短信
    /*
     * 新订单通知：SMS_225925355 {新订单提醒}-您好，军网平台有新的订单，单号：${order}，金额：${money}。地址：${address}。请及时处理。
     * 到账通知：SMS_225910508 {客户款到账提醒}-尊敬的合作伙伴您好，军网平台订单，单号：${order}，金额：${money}。客户款已到账，请及时查看，如有疑问可点击系统质疑按钮。
     * 付款通知：SMS_225935234 {货款支付提醒}-尊敬的合作伙伴您好，军网平台订单，单号：${order}，金额：${money}。货款已支付，请及时查看，如有疑问可点击系统质疑按钮。
     */
    public function sendMsg($phone, $tpl_code, $param)
    {
        $post_json = json_encode($param);
        $client = self::createClient();
        $sendSmsRequest = new SendSmsRequest ([
            "signName" => "泰龙吉",
            "phoneNumbers" => $phone,
            "templateCode" => $tpl_code,
            "templateParam" => $post_json
        ]);
        $client->sendSms($sendSmsRequest);
    }

    public static function createClient()
    {
        $accessKeyId = 'LTAIeRWUxR6rp7sj';
        $accessKeySecret = 'n4qEWLCengJ012UAWl7UJvMOVMLgXY';
        $config = new Config ([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi ($config);
    }
}